Valid palindrome

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

For example, "A man, a plan, a canal: Panama" is a palindrome. "race a car" is not a palindrome.

class Solution(object):
    def isPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        #print s, ' ', len(s)
        if not s or len(s) == 1: # empty strings or strings with 1 char
            return True

        s = s.lower()   #convert the entire string to lowercase
        start = 0
        end = len(s) - 1

        while start < end:
            if not s[start].isalnum():
                start += 1
                continue
            if not s[end].isalnum():
                end -= 1
                continue

            if s[start] != s[end]:
                return False

            start += 1
            end   -= 1

        return True

Last updated

Was this helpful?