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

Leetcode[20]-Valid Palindrome

时间:2015-06-11 14:38:52      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:characters   string   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.


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

标签:characters   string   valid   palindrome   回文串   

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

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