小小程序媛  
得之坦然,失之淡然,顺其自然,争其必然

题目

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.

分析

判断给定字符串是否为忽略大小写,特殊符号,空格等之后的回文串。

AC代码

class Solution {
public:
    bool isPalindrome(string s) {
        if (s.empty())
            return true;

        int size = s.length();

        int lhs = 0, rhs = size - 1;
        while (lhs < rhs)
        {
            if (!isalpha(s[lhs]))
            {
                ++lhs;
                continue;
            }
            if (!isalpha(s[rhs]))
            {
                --rhs;
                continue;
            }//if

            if (s[lhs] != s[rhs])
                return false;
            else
            {
                ++lhs;
                --rhs;
            }

        }//while
        return true;
    }
    //判断是否是字母数字,如果是大写字母则将其转化为小写字母
    bool isalpha(char &c){
        if ((c >= 'A'&&c <= 'Z')){
            c = c - 'A' + 'a';
            return true;
        }
        return (c >= 'a'&&c <= 'z') || (c >= '0'&&c <= '9');
    }
};

GitHub测试程序源码

posted on 2015-10-21 13:10  Coding菌  阅读(146)  评论(0编辑  收藏  举报