[LeetCode] Valid Palindrome

Posted immjc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 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.

判断回文是否有效。

思路:首先先将给定字符串中字母和数字挑选出来,并将大写字母统一改写成小写字母

然后利用二分查找判断回文

class Solution {
public:
    bool isPalindrome(string s) {
        string pattern = pickAlphanumeric(s);
        int left = 0, right = pattern.size() - 1;
        while (left <= right) {
            if (pattern[left] == pattern[right]) {
                left++;
                right--;
            }
            else {
                break;
            }
        }
        if (left > right)
            return true;
        else
            return false;
    }
    
    string pickAlphanumeric(string& s)
    {
        string res;
        for (auto& c : s) {
            if (isalnum(c)) {
                if (isdigit(c))
                    res += c;
                else
                    res += tolower(c);
            }
        }
        return res;
    }
};
// 9 ms

 




以上是关于[LeetCode] Valid Palindrome的主要内容,如果未能解决你的问题,请参考以下文章

#Leetcode# 20.Valid Parentheses

LeetCode Valid Word Square

leetcode20. Valid Parentheses

LeetCode-Valid Palindrome

LeetCode 242. Valid Anagram

leetcode 242. Valid Anagram