美文网首页
LeetCode 125. Valid Palindrome

LeetCode 125. Valid Palindrome

作者: 洛丽塔的云裳 | 来源:发表于2020-04-26 23:17 被阅读0次

0.前言

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.

Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true

Example 2:
Input: "race a car"
Output: false

1. c++版本

注意 isalnum : 当c是字母或数字时为真; ** isalpha** : 当c是字母时为真; isdigit : 当c是数字时为真

class Solution {
public:
    bool isPalindrome(string s) {
        for (int i=0, j=s.size()-1; i<=j; ) {
            if (s[i] == ' ' or !isalnum(s[i]))
                ++i;
            else if (s[j] == ' ' or !isalnum(s[j]))
                --j;
            else {
                if (tolower(s[i]) != tolower(s[j]))
                    return false;
                ++i; --j;
            }
        }
        return true;  
    }
};

2. python版本

class Solution(object):
    def isPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        i, j = 0, len(s)-1
        while i<j:
            if s[i].isspace() or not s[i].isalnum():
                i += 1
            elif s[j].isspace() or not s[j].isalnum():
                j -= 1
            else:
                if s[i].lower() == s[j].lower():
                    i += 1
                    j -= 1
                else:
                    return False
        return True

相关文章

网友评论

      本文标题:LeetCode 125. Valid Palindrome

      本文链接:https://www.haomeiwen.com/subject/appswhtx.html