125. Valid Palindrome

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

Note: For the purpose of this problem, we define empty string as valid palindrome.

Example 1:

Input:
 "A man, a plan, a canal: Panama"

Output:
 true

Example 2:

Input:
 "race a car"

Output:
 false

Thoughts:

  1. Lower-case the string and have two pointers starting from first and last to check the legit characters until two pointers cross each other over

Code: Two pointers explicit

class Solution(object):
    def isPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        s = s.lower()
        i , j = 0, len(s) - 1
        while i <= j:
            while i < j and not s[i].isalnum(): # must be i < j in order to prevent index out of range. e.g ".,"
                i +=1

            while i < j and not s[j].isalnum(): # must be i < j in order to prevent index out of range. e.g ".,"
                j -= 1

            if s[i] != s[j]: return False 
            i+= 1;  j -= 1

        return True

Code: Two pointers implicit (by comparing the reverse of the string itself)

class Solution(object):
    def isPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        s = ''.join(e for e in s if e.isalnum()).lower()

        return s == s[::-1]

results matching ""

    No results matching ""