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

Constraints:

  • s consists only of printable ASCII characters.

Solution:

class Solution:
def isPalindrome(self, s: str) -> bool:
N = len(s)
left = 0
right = N - 1
while left < N - 1 and not s[left].isalnum():
left += 1
while right > 0 and not s[right].isalnum():
right -= 1
while left < right:
if s[left].lower() != s[right].lower():
return False

left += 1
while not s[left].isalnum():
left += 1
right -= 1
while not s[right].isalnum():
right -= 1
return True

Link

Reference

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store