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.
题意解读:判断一个string是否为palindrome(回文),即该string从头至尾与从尾至头的字符出现顺序是否一样如“abccba”。
<pre name="code" class="cpp">bool isPalindrome(string s) {
//戴的方法
::transform(s.begin() , s.end() , s.begin() , ::tolower);
string::iterator left=s.begin() , right=prev(s.end());
while(left<right){
if(!isalnum(*left)){
++left;
}else if(!isalnum(*right)){
--right;
}else if(*left==*right){
++left;
--right;
}else{
return false;
}
}
return true;
//我的方法
::transform(s.begin() , s.end() , s.begin() , ::tolower);
string::iterator left = s.begin() , right = prev(s.end());
while(left<right){
while(!isalnum(*left)){
++left;
if(left==s.end()){ //如果left==s.end(),则说明该字符串不为空且,一直没有出现字母和数字如“。。。。。。”
return true;
}
}
while(!isalnum(*right)){
--right;
}
if(*left==*right){
++left;
--right;
}else{
return false;
}
}
return true;
}