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

LeetCode Valid Palindrome

时间:2015-05-01 18:46:29      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

1.题目


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.

2.解答


首先是题目的意思是:判断一个句子,正的读和倒着读是否都一样。比如"abba",就是正读和倒读都一样。这题只是多少忽略大小写,忽略非字母和数字。所以"A man, a plan, a canal: Panama"正读和倒读是一样的。


class Solution {
public:
    bool isValideChar(char c){
        if(c >= ‘A‘ && c <= ‘Z‘){
            return true;
        }
        if(c >= ‘a‘ && c <= ‘z‘){
            return true;
        }
        if(c >= ‘0‘ && c <= ‘9‘){
            return true;
        }
        return false;
    }
    char tolowerCase(char c){
        if(c >= ‘A‘ && c <= ‘Z‘){
            return c - ‘A‘ + ‘a‘;
        }else{
            return c;
        }
    }
    bool isPalindrome(string s) {
        int left = 0;
        int right = s.size() - 1;
        if(s.size() == 0){
            return true;
        }
        int sSize = s.size();
        while((isValideChar(s[left]) == false) && left < s.size()){
                   ++left;
                }
                while((isValideChar(s[right]) == false) && right >= 0){
                   --right;
                }
        while(left < right){
            
            if(tolowerCase(s[left]) == tolowerCase(s[right])){
                ++left;
                while((isValideChar(s[left]) == false) && left < s.size()){
                   ++left;
                }
                --right;
                while((isValideChar(s[right]) == false) && right >= 0){
                   --right;
                }
            }else{
                return false;
            }
        }
        return true;
    }
};

还是比较容易的,一个指向前,一个指向后,进行比较,过滤掉非字母数字。

http://www.waitingfy.com/archives/1680

LeetCode Valid Palindrome

标签:

原文地址:http://blog.csdn.net/fox64194167/article/details/45420559

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