首页 > 代码库 > Valid Palindrome

Valid Palindrome

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 ignorecase(char a,char b)    {        if(ok2(a)&&ok2(b)) //若是字母,忽略大小写            return a==b||a==(b+32)||a==(b-32)||(a+32)==b||(a-32)==b;             else//否则是数字,直接比较            return a==b;    }    bool ok(char a)    {        return (a>=0&&a<=9)||(a>=a&&a<=z)||(a>=A&&a<=Z);    }    bool ok2(char a)    {        return (a>=a&&a<=z)||(a>=A&&a<=Z);    }    bool isPalindrome(string s) {        if(s.empty()||s.size()==1)          return true;         int len=s.size();         int i,j,q;         for(q=0;q<s.size();++q)         {             if(ok(s[q]))                break;         }         if(q==s.size())//全部是非字母            return true;         for(i=0,j=len-1;i<j;++i,--j)//两指针从头和尾向中间缩进,遇到非字母跳过         {             if(ok(s[i])&&ok(s[j]))             {                 if(!ignorecase(s[i],s[j]))                    return false;             }             else if(ok(s[i])&&!ok(s[j])){--i;}//j位置为符号,所以i维持在原来位置             else if(!ok(s[i])&&ok(s[j])){++j;}         }         if(i==j||i==(j+1))            return true;        else            return false;    }};

 

Valid Palindrome