目录
- 1 题目
- 2 解答
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 * 105
s
仅由可打印的 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 andthere is at least one character in the string."""pass
直接双指针结束
class Solution:def isPalindrome(self, s: str) -> bool:n = len(s)left = 0right = n-1res = Truewhile left<right:if (not s[left].isalnum()):left += 1if (not s[right].isalnum()):right -= 1if (s[left].isalnum() and s[right].isalnum()):if s[left].lower() == s[right].lower():left += 1right -= 1else :res = Falsebreakreturn res