【leetcode】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.

空串是回文串。

分析:首尾開始比較。不是字母的跳过,都是字母且同样继续比較,否则就是返回false。

 bool alphanumeric (char c)
    {
        return (c >= 'a' && c <= 'z' || c >= '0' && c <= '9');
    }
    void tolower(string &s)
    {
        for(int i = 0; i < s.size(); ++i)
        if(s[i] <= 'Z' && s[i] >= 'A')
        s[i] += 32;
    }
    bool isPalindrome(string s) {
        if(s.size() <= 1) return true;
        int i = 0;
        int j = s.size() - 1;
        tolower(s);
        while(i <= j)
        {
            if(alphanumeric(s[i]) && alphanumeric(s[j]) && s[i] == s[j])
            {++i; --j;}
            else if(!alphanumeric(s[i])) ++i;
            else if(!alphanumeric(s[j])) --j;
            else  return false;
        }
        return true;
    }


版权声明:本文博客原创文章,博客,未经同意,不得转载。

posted on 2015-07-26 12:05  gcczhongduan  阅读(114)  评论(0编辑  收藏  举报