125. 验证回文串

Difficulty
easy
Tags
双指针
字符串
Star
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例 1:
输入: "A man, a plan, a canal: Panama" 输出: true 解释:"amanaplanacanalpanama" 是回文串
示例 2:
输入: "race a car" 输出: false 解释:"raceacar" 不是回文串
提示:
  • 1 <= s.length <= 2 * 105
  • 字符串 s 由 ASCII 字符组成

双指针

思路
采用相向双指针,一前一后来遍历该字符串。
重点关注的点在与在遍历的过程中,如何通过while循环跳过不相关的字符。
题解
class Solution: def isPalindrome(self, s: str) -> bool: if len(s) <= 1: return True left, right = 0, len(s) - 1 while left < right: while left < right and not self.isValid(s[left]): left += 1 while left < right and not self.isValid(s[right]): right -= 1 if s[left].lower() != s[right].lower(): return False left += 1 right -= 1 return True def isValid(self, char): return char.isdigit() or char.isalpha()