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"isnota palindrome.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
Solution 1: Two Pointers
Idea:
Two pointer: one loop forward, one loop backward.
Use function string.isalnum() to check if the character is alphanumeric.
Time Complexity: O(n)
Space Complexity: O(1)
defisPalindrome(s):""" :type s: str :rtype: bool"""# convert to lowercase s = s.lower()# two pointers left =0 right =len(s)-1while left < right:ifnot s[left].isalnum(): left +=1elifnot s[right].isalnum(): right -=1elif s[left]!= s[right]:returnFalseelse: left +=1 right -=1returnTrue
Solution 2: Recursive
Idea:
Handle from outside to inside. Use the same function recursively.