LeetCode 125: Valid Palindrome

link

Try matching lowercase left and right skipping over non-alphanumeric characters.

Time: \mathcal{O}(n), space: \mathcal{O}(1).

class Solution:
    def isPalindrome(self, s: str) -> bool:
        left, right = 0, len(s)-1
        while left < right:
            if not s[left].isalnum():
                left += 1
                continue
            if not s[right].isalnum():
                right -= 1
                continue
            if s[left].lower() != s[right].lower():
                return False
            left += 1
            right -= 1
        return True

Leave a comment