![](/img/trans.png)
[英]"It's a Palindrome!" or "It's not a Palindrome!" are not printing when the string has spaces. How do I properly account for the spaces in a string?
[英]How do I handle Palindrome with spaces in python?
我正在尝试使用双端队列检查 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)))
在开始 function 的逻辑之前,您必须删除空格:
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)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.