这个简单,队列可两边进两边出。
# coding = utf-8 # 双向进出队列 class Deque: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def size(self): return len(self.items) def add_front(self, item): self.items.append(item) def add_rear(self, item): self.items.insert(0, item) def remove_front(self): return self.items.pop() def remove_rear(self): return self.items.pop(0) # 回文检查 def pal_check(check_str): deque = Deque() for item in check_str: deque.add_front(item) is_pal = True # 如果奇数文字,最后一个可不用对比 while deque.size() > 1 and is_pal: # 比较前端和后端进出队列是否相同 if deque.remove_front() != deque.remove_rear(): is_pal = False return is_pal print(pal_check('radar')) print(pal_check('toot')) print(pal_check('tooth')) print(pal_check('4356sdfgdsad678'))