https://leetcode.com/problems/valid-palindrome/
第一步验证只有数字和字母,
第二步字符串反转
第三步比较是否相等
# -*- coding: utf-8 -*
# @lc app=leetcode.cn id=125 lang=python3
#
# [125] 验证回文串
#
# @lc code=start
# class Solution:
# def isPalindrome(self, s: str) -> bool:
# s = [i for i in s.lower() if i.isalnum()]
# return s == s[::-1]
class Solution:
def isPalindrome(self, s: str) -> bool:
i, j = 0, len(s) - 1
while i < j:
a, b = s[i].lower(), s[j].lower()
if a.isalnum() and b.isalnum():
if a != b: return False
else:
i, j = i + 1, j - 1
continue
i, j = i + (not a.isalnum()), j - (not b.isalnum())
return True
网友评论