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

[LintCode] Valid Palindrome 验证回文字符串

时间:2016-08-03 06:43:44      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:

 

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

Notice

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.

 
Example

"A man, a plan, a canal: Panama" is a palindrome.

"race a car" is not a palindrome.

Challenge

O(n) time without extra memory.

 

LeetCode上的原题,请参见我之前的博客Valid Palindrome

 

解法一:

class Solution {
public:
    /**
     * @param s A string
     * @return Whether the string is a valid palindrome
     */
    bool isPalindrome(string& s) {
        int left = 0, right = s.size() - 1;
        while (left < right) {
            if (!isAlNum(s[left])) ++left;
            else if (!isAlNum(s[right])) --right;
            else if ((s[left] + 32 - a) % 32 != (s[right] + 32 - a) % 32) return false;
            else {
                ++left; --right;
            }
        }
        return true;
    }
    bool isAlNum(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;
    }
};

 

解法二:

class Solution {
public:
    /**
     * @param s A string
     * @return Whether the string is a valid palindrome
     */
    bool isPalindrome(string& s) {
        int left = 0, right = s.size() - 1;
        while (left < right) {
            if (!isalnum(s[left])) ++left;
            else if (!isalnum(s[right])) --right;
            else if ((s[left] + 32 - a) % 32 != (s[right] + 32 - a) % 32) return false;
            else {
                ++left; --right;
            }
        }
        return true;
    }
};

 

[LintCode] Valid Palindrome 验证回文字符串

标签:

原文地址:http://www.cnblogs.com/grandyang/p/5731347.html

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