# 利用雙指標,一次遍歷,求出結果
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"))
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/98273.html
標籤:Python
