Question
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
"A man, a plan, a canal: Panama"is a palindrome.
"race a car"is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
Solution
把不是数字和字母的字符先去掉,然后统计大小写,最后判断是否为回文。
Code
class Solution {
public:
bool isPalindrome(string s) {
if (s.empty())
return true;
string str;
for (char c : s) {
if (isDigitAlpha(c)) {
if (c >= 'a' && c <= 'z')
c -= 32;
str += c;
}
}
s = str;
return isPalindromeCore(s, 0, s.length() - 1);
}
bool isDigitAlpha(char c) {
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) {
return true;
}
return false;
}
bool isPalindromeCore(string s, int start, int end) {
while (start <= end) {
if (s[start++] != s[end--])
return false;
}
return true;
}
};