题目链接
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
python代码实现:
import re
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
# res = re.sub('\'|\"|-|#|@|,|:|\.|\?|\ ', '', s).lower()
# return res == res[::-1]
res = [i.lower() for i in s if i.isalnum()]
return res == res[::-1]
s = Solution()
res = s.isPalindrome("A man, a plan, a canal -- Panama")
print(res)
实现思路:
可以通过代码注释部分的正则表达式来进行字符的替换,然后在比较是否是正文序列,但是需要替换的特殊字符太多,于是转换思路,通过列表表达式的方式明显效率会更高一些。