类的声明:
class deque:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == [] # python中的列表就像是一个栈
def size(self):
return len(self.items)
def addFront(self, item):
self.items.append(item) # 注意这里不是push
def addRear(self, item):
self.items.insert(0, item)
def removeFront(self):
self.itmes.pop()
def removeRear(self):
self.items.pop(0)
代码
class deque:
from pythonds.basic.deque import Deque
def Palindrome(sentence):
words = []
charDeque = Deque()
for word in sentence:
charDeque.addRear(word) # 从尾部加入更加符合习惯
while charDeque.size() > 1:
word1 = charDeque.removeFront()
word2 = charDeque.removeRear()
if word1 != word2:
return False
return True
print(Palindrome("上海自来水来自海上"))