我正在尝试使用双端队列在 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)))
在开始函数的逻辑之前,您必须删除空格:
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)))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句