码迷,mamicode.com
首页 > 其他好文 > 详细

25. Valid Palindrome

时间:2014-08-27 01:39:08      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   strong   for   ar   div   

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 0;
}
inline char getLastChar(string &s, int& h) {
    while(h >= 0) {
        char ch = getLowerChar(s, h);
        if(ch) return ch;
        --h;
    }
    return 0;
}
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;
        
    }
};

 

25. Valid Palindrome

标签:style   blog   color   os   io   strong   for   ar   div   

原文地址:http://www.cnblogs.com/liyangguang1988/p/3938555.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!