题目:
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)
{
for(int i = 0 , j = s.size() - 1 ; i < j ; i++ , j--)
{
while(!isalnum(s[i]) && i < j)
i++;
while(!isalnum(s[j]) && i < j)
j--;
if(tolower(s[i]) != tolower(s[j]))
return false;
}
return true;
}
};