# 利用雙指針,一次遍歷,求出結果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 TrueA = Solution()print(A.isPalindrome("A man, a plan, a canal: Panama"))print(A.isPalindrome(""))print(A.isPalindrome("qq"))print(A.isPalindrome("race a car"))