码迷,mamicode.com
首页 > 其他好文 > 详细

Valid Palindrome

时间:2014-11-03 22:26:42      阅读:304      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   ar   os   for   sp   div   

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

标签:style   blog   io   color   ar   os   for   sp   div   

原文地址:http://www.cnblogs.com/fightformylife/p/4072230.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!