验证字符串是否为回文串125

题目:给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。

说明:本题中,我们将空字符串定义为有效的回文串。

输入:”A man, a plan, a canal: Panama”

输出:True

思路:先将字符串转换为list(只考虑字母和数字且将字母都转换为小写),再前后夹击看字符是否一致

1
2
3
4
5
6
7
8
9
10
11
12
13
class :
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s = ''.join(e for e in s.lower() if e.isalnum())
if s:
half_len = len(s) // 2 + 1
for index in range(half_len):
if s[index] != s[len(s) - 1 - index]:
return False
return True

例子

1
2
3
s =  "race a car"
print(Solution().isPalindrome(s))
print(string.punctuation)