题目:
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例 1:
输入: "A man, a plan, a canal: Panama"
输出: true
示例 2:
输入: "race a car"
输出: false
解答:
思路:字符串去掉标点和空格后反转,反转前与反转后相同。
方法一:
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
import string
from copy import deepcopy
enstr = string.ascii_lowercase + string.digits
a = [i for i in s.lower() if i in enstr]
b = deepcopy(a)
a.reverse()
return a == b
方法二:使用string的内置函数isdigit()和isalpha()。
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
res=[]
for x in s:
if x.isdigit():
res.append(x)
elif x.isalpha():
res.append(x.lower())
return res==res[::-1]
方法三:使用string的内置函数isalnum()。
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s = ''.join(filter(str.isalnum,s)).lower()
return s==s[::-1]
方法四:使用正则匹配。
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
import re
s = ''.join(re.findall(r"[0-9a-zA-Z]", s)).lower()
return s == s[::-1]
方法五:使用正则匹配。
import re
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s = re.sub("[^A-Za-z0-9]+", "", s).lower()
return s == s[::-1]