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

简介:

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.

"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;
    }
};

本文转自博客园Grandyang的博客,原文链接:验证回文字符串[LintCode] Valid Palindrome ,如需转载请自行联系原博主。

相关文章
|
机器学习/深度学习
CF1304B Longest Palindrome(可逆转符号,数学分析,回文串)
CF1304B Longest Palindrome(可逆转符号,数学分析,回文串)
76 0
|
算法 Java 程序员
【手绘算法】力扣 20 有效的括号(Valid Parentheses)
Hi,大家好,我是Tom。一个美术生转到Java开发的程序员。今天给大家分享的是力扣题第20题,有效的括号。在解题过程中,也会手写一些伪代码。当然,如果想要完整的源码的话,可以到我的个人主页简介中获取。 这道题呢比较简单,但是曾经成为B站的算法面试题,而且通过率只有44.5%。
114 0
|
C++
【PAT甲级 - C++题解】1040 Longest Symmetric String
【PAT甲级 - C++题解】1040 Longest Symmetric String
117 0
LeetCode contest 187 1437. 是否所有 1 都至少相隔 k 个元素 Check If All 1's Are at Least Length K Places Away
LeetCode contest 187 1437. 是否所有 1 都至少相隔 k 个元素 Check If All 1's Are at Least Length K Places Away
|
canal
ARTS-14--回文字符串的解法
ARTS-14--回文字符串的解法
115 0
LeetCode之Palindrome Number(回文数)
LeetCode之Palindrome Number(回文数)
82 0