[leetcode_125]Valid Palindrome

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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;
    }
};
Licensed under CC BY-NC-SA 4.0