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:
string strupr(string &s)
{
for(int i=0; i<s.size(); i++)
s[i] = toupper(s[i]);
return s;
}
bool isPalindrome(string s)
{
if(s.size() == 0)
return true;
s = strupr(s);
int l = 0;
int r = s.size() - 1;
while(l <= r)
{
while(l<r && !isalpha(s[l]) && !isdigit(s[l]))
++l;
while(l<r && !isalpha(s[r]) && !isdigit(s[r]))
--r;
if(s[l] != s[r])
return false;
++l;
--r;
}
return true;
}
};