Two Line Python 99%


  • 0
    V

    O(n) space and time

    import re
    
    class Solution(object):
        def isPalindrome(self, s):
            """
            :type s: str
            :rtype: bool
            """
            s = re.sub(r'[^a-zA-Z0-9]', '', s).lower()
            return s[::-1] == s
    

    For reference here's a O(1) space and O(n) time sol. In practice it is much slower than the above, also O(n) time.

    import re
    
    class Solution(object):
        def isPalindrome(self, s):
            """
            :type s: str
            :rtype: bool
            """
            l = 0
            r = len(s) - 1
            while l < r:
                while l < r and re.match(r'[^a-zA-Z0-9]', s[l]):
                    l += 1
                    
                while l < r and re.match(r'[^a-zA-Z0-9]', s[r]):
                    r -= 1
                
                if s[l].upper() != s[r].upper():
                    return False
                l += 1
                r -= 1
                
            return True
    

Log in to reply
 

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