Simple Python Solution - 80ms


  • 0
    A

    Idea is to simply keep two pointers, one at the end of the string and one at the beginning, comparing their two respective values with each other. If we encounter a non alphanumeric character, then we simply ignore it. Once the two pointers cross paths, we know that we have found a palindrome.

    class Solution(object):
        def isPalindrome(self, s):
            i = 0
            j = len(s) - 1; 
            while i < j:
                if not s[i].isalpha() and not s[i].isdigit():
                    i += 1
                    continue
                if not s[j].isalpha() and not s[j].isdigit():
                    j -= 1
                    continue
                if s[i].lower() != s[j].lower():
                    return False
                i+=1; j-=1
            return True
    

Log in to reply
 

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