lc125

235 阅读1分钟

125. Valid Palindrome

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

思路:头尾比较小写,如果不是字母,进位到下一位 python3

def isPalindrome(self, s: str) -> bool:
    l,r=0,len(s)-1
    while l<r:
        while l<r and not s[l].isalnum():
            l += 1
        while l<r and not s[r].isalnum():
            r -= 1
        if s[l].lower() != s[r].lower():
            return False
    return True