验证回文串
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
我的代码
class Solution:
def isPalindrome(self, s: str) -> bool:
li = []
if s.isspace():
return True
for each in s:
if each.isalnum():
li.append(each)
else:
continue
# 双指针
low = 0
high = len(li) - 1
while low < high:
if li[low].upper() == li[high].upper():
low = low + 1
high = high - 1
else:
return False
# 循环退出时,low== high,此时,说明都相等
return True
别人的代码:
class Solution:
def isPalindrome(self, s: str) -> bool:
s = s.lower()
left, right = 0, len(s) - 1
while left < right:
# 两个循环找到左侧和右侧为字母或者数字的位置
while left < len(s) - 1 and not s[left].isalnum():
left += 1
while right > 0 and not s[right].isalnum():
right -= 1
if left >= right: # 判断移动过后的left right是否满足left在左,right在右的相对位置
break
else:
if s[left] != s[right]: # 如果左右指针所指不同,则肯定不构成回文
return False
else: # 左右指针各前进一步
left += 1
right -= 1
return True
另一思路:正则表达式
^ [a-zA-Z]是去匹配目标字符串中以中括号中的a—z或者A—Z开头的字符
[^a-zA-Z]是去匹配目标字符串中非a—z也非A—Z的字符
import re
class Solution:
def isPalindrome(self, s: str) -> bool:
# re.sub(正则表达式,新内容,string) 替换
s=re.sub('[^a-zA-Z0-9]','',s)
s=s.lower()
return s==s[::-1]