Valid palindrome#

Levels: level-2
Data structures: string

LeetCode

Description#

  • 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.

Examples#

1Input: "A man, a plan, a canal: Panama"
2Output: true
1Input: "race a car"
2Output: false

Python Solution#

 1class Solution(object):
 2    def isPalindrome(self, s):
 3        """
 4        :type s: str
 5        :rtype: bool
 6        """
 7
 8        l, r = 0, len(s) - 1
 9        while l < r:
10            while l < r and not s[l].isalnum():
11                l += 1
12            while l < r and not s[r].isalnum():
13                r -= 1
14            if s[l].lower() != s[r].lower():
15                return False
16            l += 1
17            r -= 1
18        return True
19
20    # Use pythonic inbuilt functions
21    def isPalindromeInbuilt(self, s):
22        s = ''.join(e for e in s if e.isalnum()).lower()
23        return s == s[::-1]