给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例 1:
输入: “A man, a plan, a canal: Panama”
输出: true
解释:“amanaplanacanalpanama” 是回文串
示例 2:
输入: “race a car”
输出: false
解释:“raceacar” 不是回文串
提示:
1 <= s.length <= 2 * 105
字符串 s 由 ASCII 字符组成
我的解法:
class Solution:
def isPalindrome(self, s: str) -> bool:
newStr = ''.join(filter(str.isalnum, s)) # 字符串过滤
newStr_l = newStr.lower()
n = len(newStr_l)//2
lists = []
for i,ch in enumerate(newStr_l):
lists.append(ch)
a = 0
for j in range(n):
if lists[j] == lists[len(newStr_l)-j-1]:
a += 1
if a == n:
return True # 可参考官解先判断F,这样就不需要a了。
return False
官方解法:https://leetcode-cn.com/problems/valid-palindrome/solution/yan-zheng-hui-wen-chuan-by-leetcode-solution/
解法一:筛选 + 翻转判断
class Solution:
def isPalindrome(self, s: str) -> bool:
sgood = "".join(ch.lower() for ch in s if ch.isalnum())
return sgood == sgood[::-1] # 翻转
解法二:筛选+双指针判断
class Solution:
def isPalindrome(self, s: str) -> bool:
sgood = "".join(ch.lower() for ch in s if ch.isalnum())
n = len(sgood)
left, right = 0, n - 1
while left < right:
if sgood[left] != sgood[right]:
return False
left, right = left + 1, right - 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
复杂度分析:
时间复杂度:O(|s|),其中 |s| 是字符串 s 的长度。
空间复杂度:O(1)。
字符串过滤:https://blog.csdn.net/huoyuanshen/article/details/83106608
力扣 (LeetCode)链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xne8id/