题目内容:
开心消消乐我们都熟悉,我们可以用刚学过的栈来做一个“一维”的开心消消乐游戏,这个游戏输入一串字符,逐个消去相邻的相同字符对。如果字符全部被消完,则输出不带引号的“None”
输入格式:
一个字符串,可能带有相邻的相同字符,如“aabbbc”
输出格式:
一个字符串,消去了相邻的成对字符,如“bc”
代码:
class Stack(object):
def __init__(self):
self.stack = [] #存放元素
def push(self, data):
self.stack.append(data)
def pop(self):
if self.stack:
self.stack.pop()
else:
raise IndexError('pop from an empty stack')
def peek(self):
if self.stack:
return self.stack[-1]
def is_empty(self):
return not bool(self.stack)
def size(self):
return size(self.stack)
def Remove(s):
stack = Stack()
str = []
for i, v in enumerate(s):
if i == 0:
stack.push(v)
else:
if v == stack.peek():
stack.pop()
else:
stack.push(v)
if stack.is_empty():
print(None)
else:
while not stack.is_empty():
str.append(stack.peek())
stack.pop()
return ''.join(str[::-1])