class Deque:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def addFront(self, item):#从队首加入
self.items.append(item)
def addRear(self, item):#从队尾加入
self.items.insert(0,item)
def removeFront(self):#从队首删除
return self.items.pop()
def removeRear(self):#从队尾删除
return self.items.pop(0)
def size(self):
return len(self.items)
def judge(s):
s=list(s)
double_queue=Deque()
i=0
a=2
while i!=len(s):
double_queue.addFront(s[i])
i+=1
# print(double_queue.items)
while not double_queue.isEmpty() and double_queue.size()!=1:
if double_queue.removeFront()==double_queue.removeRear() :
continue
else:
break
if double_queue.isEmpty() or double_queue.size()==1:
return True
else:
return False
print(judge('123321'))
print(judge('radar'))
print(judge('123341'))
print(judge('上海自来水来自海上'))
def judge2(s):#尝试降低复杂度
s=list(s)
double_queue=Deque()
for i in s:
double_queue.addFront(i)
bool=True
while double_queue.size()>1 and bool:#考虑剩余数是奇数和偶数的情况
first=double_queue.removeFront()
second=double_queue.removeRear()
if first!=second:
bool=False
return bool
print(judge2('123321'))
print(judge2('radar'))
print(judge2('123341'))
print(judge2('上海自来水来自海上'))
|