Problem Definition:
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.
Note:
Are you consider that the string might is empty? This was a good question to ask during a interview.
For the purpose of this problem, we define empty string as valid palindrome.
solution 1:using Regular expression.
1 defIspalindrome (self, s):2P=re.compile ('\w')3Arr=P.findall (s)4N=len (arr)/25 forIinchrange (n):6 ifArr[i].upper ()!=arr[n-1-i].upper ():7 returnFalse8 returnTrue
Solution 2: A simpler of the using regular expression.
1 def Ispalindrome (self, s): 2 s = re.sub ("[^a-za-z0-9]"""", s). Lower () # can be replaced by ' \w '3 return s = = S[::-1]
Solution 3:just traverse the string.
1 def Ispalindrome (s): 2 "' for inch if Ch.isalnum ()). Lower ()3 return S1 = = S1[::-1]
leetcode#125 Valid palindrome