Python solution using two pointers and a set


  • 0

    So my solution is setting two pointers left and right, and make them move toward each other. Both of them would skip unimportant characters like '?'. A valid palindrome would make s[left] == s[right] in every step.

    from string import punctuation
    def isPalindrome(self, s):
        skip_items = set(punctuation)
        skip_items.add(' ')
    
        left, right = 0, len(s) - 1
        while left < right:
            # Skip the unimportant chars
            while s[left] in skip_items:
                left += 1
                if left == right:
                    return True
            while s[right] in skip_items:
                right -= 1
                if left == right:
                    return True
    
            # Compare the left and the right
            if s[left].lower() != s[right].lower():
                return False
            left += 1
            right -= 1
    
        return True

  • 0

    A much easier and more pythonic solution is here, which uses filter() and reversed comparison.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.