25. Valid Palindrome

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.

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.

思想:简单的从两端来逐个读字符,判断是否相等。(36ms)

inline char getLowerChar(string &s, int id) {
    if((s[id] >= 'a' && s[id] <= 'z') || (s[id] >= '0' && s[id] <= '9')) return s[id];
    else if(s[id] >= 'A' && s[id] <= 'Z')  return s[id] + 32;
    else return 0;
}
inline char getFirstChar(string &s, int& l) {
    while(l < s.size()) {
        char ch = getLowerChar(s, l);
        if(ch) return ch;
        ++l;
    }
    return '*';
}
inline char getLastChar(string &s, int& h) {
    while(h >= 0) {
        char ch = getLowerChar(s, h);
        if(ch) return ch;
        --h;
    }
    return '#';
}
class Solution {
public:
    bool isPalindrome(string s) {
        int l = 0, h = s.size()-1;
        while(l <= h) {
            if(getFirstChar(s, l) != getLastChar(s, h)) 
                return false;
                ++l, --h;
        }
        return true;
        
    }
};
原文地址:https://www.cnblogs.com/liyangguang1988/p/3938555.html