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.
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.
bool alphanum(char s)
{
if (s>='0' && s<='9')return true;
if (s>='a' && s<='z')return true;
if (s>='A' && s<='Z')return true;
return false;
}
bool isPalindrome(string s) {
int i = 0, j = s.length()-1;
if(j<1)return true;
while(i<j)
{
if(s[i]>='A' && s[i]<='Z')s[i] += 32;
if(s[j]>='A' && s[j]<='Z')s[j] += 32;
if(!alphanum(s[i])){
i++;
continue;
}
else if(!alphanum(s[j]))
{
j--;
continue;
}
if(s[i] != s[j])return false;
i++;
j--;
}
return true;
}
No comments:
Post a Comment