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.
My C++ solution!
string characterOnly(string str)
{
int len=str.length();
string r;
for(int i=0;i<len;i++)
{
if(('A'<=str[i]&&str[i]<='Z')||('a'<=str[i]&&str[i]<='z')||('0'<=str[i]&&str[i]<='9'))
r.append(1,toupper(str[i]));
else
continue;
}
return r;
}
bool isPalindrome(string s)
{
s=characterOnly(s);
int len=s.length();
for(int i=0;i<(len+1)/2;i++)
{
if(s[i]!=s[len-i-1])
return false;
}
return true;
}