leetcode125

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:

Idea

the python string operations:
string1.join([….])
string2.lower()

Code

Mine

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
if not s:
return True
l, r = 0, len(s) - 1
while l < r:
while l < r and (not (s[l].isalpha() or s[l].isdigit())):
l += 1
while l < r and (not (s[r].isalpha() or s[r].isdigit())):
r -= 1
if s[l].lower() != s[r].lower():
return False
l += 1
r -= 1
return True

more concise

1
2
3
4
5
6
7
8
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s = ''.join([x for x in s if x.isalpha() or x.isdigit()]).lower()
return s == s[::-1]