首页 > 其他 > 详细

Leetcode[20]-Valid Palindrome

时间:2015-06-11 14:36:16      阅读:257      评论:0      收藏:0      [点我收藏+]

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.


思路:定义两个标示符,一个指向字符串前面,一个指向字符串末尾,如果前后位置的字符不是字母或是数字,则直接跳过该字符,如果是大写,则转换成小写再比较,如果碰到不匹配的直接返回false。

Code(C++):

class Solution {
public:

    bool isPalindrome(string s) {

        int length = s.length();

        if(length == 0){  
            return true;  
        }  
        int i = 0, j = length-1;

        while(i <= j){
            if(!isStr(s[i])) i++;
            else if(!isStr(s[j])) j--;
            else if(s[i++] != s[j--]) return false;
        }
        return true;
    }


    bool isStr(char &a){
        if(a >= ‘0‘ && a <= ‘9‘ ) {
            return true;
        }else if(a >= ‘a‘ && a <= ‘z‘ ) {
            a -= 32;
            return true;
        } else if(a >= ‘A‘ && a <= ‘Z‘ ) {
            return true;
        } 
        return false;
    }

};

Leetcode[20]-Valid Palindrome

原文:http://blog.csdn.net/dream_angel_z/article/details/46456991

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!