我正在嘗試使用雙端佇列在 python 中檢查字串是否為回文。但是下面的代碼只是檢查一個沒有空格的字串,我怎樣才能將它調整為一個處理帶空格的字串的代碼呢?例如:它僅在我將輸入寫為“BORROWORROB”時才有效,但在輸入為“BORROW OR ROB”時無效
from pythonds.basic import Deque
def isPalindrome(word):
if word is None:
return False
if len(word) <= 1:
return True
DQ = Deque()
for w in word:
DQ.addRear(w)
while (DQ.size() > 1):
front = DQ.removeFront()
rear = DQ.removeRear()
if front != rear:
return False
return True
def readInput():
inp = input("Enter string: ")
return inp
word = readInput()
print ("Is \"{}\" a palindrome: {}".format(word, isPalindrome(word)))
uj5u.com熱心網友回復:
在開始函式的邏輯之前,您必須洗掉空格:
from pythonds.basic import Deque
def isPalindrome(word):
word = word.replace(" ", "")
if word is None:
return False
if len(word) <= 1:
return True
DQ = Deque()
for w in word:
DQ.addRear(w)
while (DQ.size() > 1):
front = DQ.removeFront()
rear = DQ.removeRear()
if front != rear:
return False
return True
def readInput():
inp = input("Enter string: ")
return inp
word = readInput()
print ("Is \"{}\" a palindrome: {}".format(word, isPalindrome(word)))
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/452502.html
標籤:Python python-3.x 算法 回文 双端队列
