跳到主要内容

Valid Palindrome

描述

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

For example,

"A man, a plan, a canal: Panama" is a palindrome. "race a car" is not a palindrome.

Note: Have you consider that the string might be empty? This is a good question to ask during an interview.

For the purpose of this problem, we define empty string as valid palindrome.

分析

代码

# Valid Palindrome
# 时间复杂度O(n),空间复杂度O(1)
def isPalindrome(s: str) -> bool:
s = s.lower()
left = 0
right = len(s) - 1
while left < right:
if not s[left].isalnum():
left += 1
elif not s[right].isalnum():
right -= 1
elif s[left] != s[right]:
return False
else:
left += 1
right -= 1
return True

相关题目