LC125 验证回文串
1 题目
如果在将所有大写字符转换为小写字符、并移除所有非字母数字字符之后,短语正着读和反着读都一样。则可以认为该短语是一个 回文串 。
字母和数字都属于字母数字字符。
给你一个字符串 s,如果它是 回文串 ,返回 true ;否则,返回 false 。
示例 1:
输入: s = "A man, a plan, a canal: Panama"
输出:true
解释:"amanaplanacanalpanama" 是回文串。
示例 2:
输入:s = "race a car"
输出:false
解释:"raceacar" 不是回文串。
示例 3:
输入:s = " "
输出:true
解释:在移除非字母数字字符之后,s 是一个空字符串 "" 。
由于空字符串正着反着读都一样,所以是回文串。
提示:
1 <= s.length <= 2 * 105s仅由可打印的 ASCII 字符组成
2 解答
在使用前需要知道几个
python的函数
def isalnum(self, *args, **kwargs): # real signature unknown
"""
Return True if the string is an alpha-numeric string, False otherwise.
A string is alpha-numeric if all characters in the string are alpha-numeric and
there is at least one character in the string.
"""
pass
直接双指针结束
class Solution:
def isPalindrome(self, s: str) -> bool:
n = len(s)
left = 0
right = n-1
res = True
while left<right:
if (not s[left].isalnum()):
left += 1
if (not s[right].isalnum()):
right -= 1
if (s[left].isalnum() and s[right].isalnum()):
if s[left].lower() == s[right].lower():
left += 1
right -= 1
else :
res = False
break
return res

浙公网安备 33010602011771号