題目:
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string s, return true if it is a palindrome, or false otherwise.
給定一個字串,檢測字母全部轉小寫,去除非數字字母的元素及空白後該字串是否對稱
ex:input:"A man, a plan, a canal: Panama"=>output:True
explanation:"amanaplanacanalpanama" is a palindrome.
解這題目時我在網上查到了isalnum()這個函數
可以用來判斷該字串是否由字母或數字組成,讓這題輕鬆許多
class Solution:
def isPalindrome(self, s: str) -> bool:
s=s.lower()
p=0
q=len(s)-1
while p<q:
while p<q and not s[p].isalnum():
p=p+1
while q>p and not s[q].isalnum():
q=q-1
if s[p].isalnum() and s[q].isalnum():
if s[p]==s[q]:
p=p+1
q=q-1
else:
return False
return True
先將字串內所有字母轉為小寫
接著一個指標從前,一個指標從後,遇到字母及數字(用isalnum判斷)才停下判斷
兩者一有不同就回傳False,直到兩個指標交錯
都沒偵測到False的狀況就回傳True
最後執行時間49ms(faster than 89.89%)
那我們下題見