如果在将所有大写字符转换为小写字符、并移除所有非字母数字字符之后,短语正着读和反着读都一样。则可以认为该短语是一个 回文串 。
字母和数字都属于字母数字字符。
给你一个字符串 s,如果它是 回文串 ,返回 true ;否则,返回 false 。
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string s, return true if it is a palindrome, or false otherwise.
解题思路
遍历一遍就好,双指针遍历的过程中判断是否是数字字母,并改为小写,然后判断头尾指针的值是否相同,需要注意的是,回文串不用考虑两个指针相等的情况,因为奇数的回文字串中间必定是对称的
AC代码
class Solution:
def isPalindrome(self, s: str) -> bool:
s = s.lower()
if len(s) <= 1:
return True
else:
cls, eos = 0, len(s) - 1
while cls <= eos:
if 'a' <= s[cls] <= 'z' or '0' <= s[cls] <= '9' :
if 'a' <= s[eos] <= 'z' or '0' <= s[eos] <= '9' :
if s[cls] != s[eos]:
return False
else:
cls += 1
eos -= 1
else:
eos -= 1
else:
cls += 1
return True
官方题解
class Solution:
def isPalindrome(self, s: str) -> bool:
n = len(s)
left, right = 0, n - 1
while left < right:
while left < right and not s[left].isalnum():
left += 1
while left < right and not s[right].isalnum():
right -= 1
if left < right:
if s[left].lower() != s[right].lower():
return False
left, right = left + 1, right - 1
return True
API补充
python库的函数
isalnum()用于判断是否是字母数字
str.lower()返回一个新的字符串,将大写转为小写,还有类似的title()函数,首字母大写