首页 » 编程之美 » 正文

[leetcode_125]Valid Palindrome

判断句子是否为回文:不区分大小写,不考虑非数字和字母的字符。

class Solution {
public:
    bool isPalindrome(string s) {
        for(int i = 0;i < s.length();i++) {
            if(s[i] >= 'A' && s[i] <= 'Z') {
                s[i] = 'a' + s[i] - 'A';
            }
        }
        int i = 0;
        int j = s.length()-1;
        while(i < j) {
            while(!isALetter(s[i]) && i < j)i++;
            while(!isALetter(s[j]) && i < j)j--;
            if(i >= j)break;
            if(s[i] != s[j])
                return false;
            else {
                i++;
                j--;
            }
        }
        return true;
    }
private:
    bool isALetter(char c) {
        if((c >= 'a' && c <= 'z')||(c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))
            return true;
        else
            return false;
    }
};

发表评论