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.
思路:题目不难,头尾向中间逼近即可,代码如下:
class Solution {
public:
bool isPalindrome(string s) {
int i = 0;
int j = s.length() - 1;
if(j < 1)
return true;
while(i <= j){
if(!isalnum (s[i]))
i++;
else if(!isalnum (s[j]))
j--;
else{
int tmp = abs(s[i] - s[j]);
if(tmp == 0 || tmp == 32){
i++;
j--;
}
else
return false;
}
}
return true;
}
};