# 利用雙指針,一次遍歷,求出結果class Solution: def isPalindrome(self, s: str) -> bool: # 定義變數,接收字元串的長度 length = len(s) # 長度小於等於1直接返回真 if length <= 1:return True # 定 ...
# 利用雙指針,一次遍歷,求出結果
class Solution:
def isPalindrome(self, s: str) -> bool:
# 定義變數,接收字元串的長度
length = len(s)
# 長度小於等於1直接返回真
if length <= 1:return True
# 定義兩個指針, 分別指向字元串頭和尾
index1,index2 = 0,length - 1
while index1 <= index2:
# 判斷字元是否為字母或者數字
if not s[index1].isalnum():
index1 += 1
continue
if not s[index2].isalnum():
index2 -= 1
continue
# 判斷兩個字元是否相同
if s[index1].lower() != s[index2].lower():
return False
index1 += 1
index2 -= 1
return True
A = Solution()
print(A.isPalindrome("A man, a plan, a canal: Panama"))
print(A.isPalindrome(""))
print(A.isPalindrome("qq"))
print(A.isPalindrome("race a car"))