125. Valid Palindrome
Question: Valid Palindrome
Solution
想法:
Palindrome:”dabbad”, “cbc”
- 這個字串是否對稱:左邊讀過來,跟右邊讀過來要一樣 → 兩個 pointer 一個從頭開始走,一個從尾開始走,每次都檢查兩個字母是否相同: s[head] == s[tail]
- 檢查到中間就可以停了,也就是 頭 > 尾 的時候: head > tail: stop!
- 跳過空格與符號:用 is_alphanum() 去檢查
class Solution:
def isPalindrome(self, s: str) -> bool:
head, tail = 0, len(s) - 1
while head < tail:
if self.is_alpha_num(s[head]):
if self.is_alpha_num(s[tail]):
if s[head].lower() != s[tail].lower():
return False
head += 1
tail -= 1
else:
tail -= 1
else:
head += 1
return True
def is_alpha_num(self, c):
return (ord("A") <= ord(c) <= ord("Z")) or (ord("a") <= ord(c) <= ord("z")) or (ord("0") <= ord(c) <= ord("9"))
Comments
Post a Comment