题目
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例 1:
输入: “A man, a plan, a canal: Panama”
输出: true示例 2:
输入: “race a car”
输出: false
思路1
从两边向中间判断,如果遇到不是字母或者数字,则判断下一个
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
if s.strip()=='':
return True
lens = len(s)
mid = lens//2
low = 0
high = lens - 1
while low <= high:
while low <= high and not s[low].isdigit() and not s[low].isalpha() :
low += 1
while low <= high and not s[high].isdigit() and not s[high].isalpha() :
high -= 1
if low >high:
return True
print(s[low].lower(),s[high].lower())
if s[low].lower() != s[high].lower():
return False
low += 1
high -= 1
return True
思路2
- 将整个字符串改成小写
- 将s整理成只含有字母和数字的字符串
- 判断s是否s的倒序相等
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s = s.lower()
target = 'abcdefghijklmnopqrstuvwxyz0123456789'
L = []
for x in s:
if x in target:
L.append(x)
return L == L[::-1]