動機

就回文

Problem

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

 

Example 1:

Input: s = A man, a plan, a canal: PanamaOutput: trueExplanation: amanaplanacanalpanama is a palindrome.

Example 2:

Input: s = race a carOutput: falseExplanation: raceacar is not a palindrome.

 

Constraints:

  • 1 <= s.length <= 2 * 105
  • s consists only of printable ASCII characters.

Sol

注意只要數字與字母

class Solution:
    def isPalindrome(self, s: str) -> bool:
        s = [c.lower() for c in s if c.isalpha() or c.isnumeric()]
        i,j = [0, len(s)-1]
        while i < j:
            if s[i] != s[j]:
                return False
            i,j = [i+1, j-1]
        return True