代码链接:https://leetcode.cn/problems/valid-palindrome/solution/yan-zheng-hui-wen-chuan-by-leetcode-solution/
注意事项:
- 所有大写字符转换为小写字符:lower() 方法转换字符串中所有大写字符为小写。
- 移除所有非字母数字字符:isalnum() 方法检测字符串是否由字母和数字组成。
使用双指针。初始时,左右指针分别指向 s g o o d sgood sgood 的两侧,随后我们不断地将这两个指针相向移动,每次移动一步,并判断这两个指针指向的字符是否相同。当这两个指针相遇时,就说明 s g o o d sgood sgood 时回文串。
# class Solution:
# def isPalindrome(self, s: str) -> bool:
# s = ''.join(ch.lower() for ch in s if ch.isalnum())
# n = len(s)
# for i in range(n//2):
# if s[i] != s[n-1-i]:
# return False
# return True
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