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 isAlpha(char a,char &t){
if((a>='a'&&a<='z')||(a>='0'&&a<='9')){
t=a;
return true;
}
if(a>='A'&&a<='Z'){
t=a+32;
return true;
}
return false;
}
bool isPalindrome(string s){
if(!s.size())return true;
int i=0,j=s.size()-1;
char ta,tb;
while(i<=j){
bool f1=isAlpha(s[i],ta);
bool f2=isAlpha(s[j],tb);
if(f1&&f2){
if(ta!=tb)return false;
i++;
j--;
}
if(!f1)i++;
if(!f2)j--;
}
return true;
}
};
answer2
class Solution{
public:
bool isAlpha(char a,char &t){
if((a>='a'&&a<='z')||(a>='0'&&a<='9')){
t=a;
return true;
}
if(a>='A'&&a<='Z'){
t=a+32;
return true;
}
return false;
}
bool isPalindrome(string s){
if(!s.size())return true;
int i=0,j=s.size()-1;
char ta,tb;
while(i<j){
while(i<j&&!isAlpha(s[i],ta))i++;
while(i<j&&!isAlpha(s[j],tb))j--;
if(i>=j)break;
if(ta!=tb)return false;
i++;
j--;
}
return true;
}
};
answer3
class Solution {
public:
bool isPalindrome(string s) {
transform(s.begin(),s.end(),s.begin(),::tolower);
auto left=s.begin(),right=prev(s.end());
while(left<right){
if(!::isalnum(*left))++left;
else if(!::isalnum(*right))--right;
else if(*left!=*right)return false;
else{++left;--right;}
}
return true;
}
};