'''
栈
实现语言: Python
有次序的数据集, 每个数据仅从栈顶一端加入和从数据集中移除
'''
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
# 入栈
def push(self, item):
self.items.append(item)
# 出栈
def pop(self):
return self.items.pop()
# Peek 偷看;一瞥,看一眼;(计算机)读取数据
def peek(self):
return self.items[len(self.items) - 1]
def size(self):
return len(self.items)
'''
使用栈进行简单括号匹配
'''
def matches(open, close):
opens = "([{"
closers = ")]}"
return opens.index(open) == closers.index(close)
def parChecker(symbolString):
s = Stack()
balanced = True
index = 0
while index < len(symbolString) and balanced:
symbol = symbolString[index]
if symbol in "([{":
s.push(symbol)
else:
if s.isEmpty():
balanced = False
else:
top = s.pop()
if not matches(top, symbol):
balanced = False
index += 1
if balanced and s.isEmpty():
return True
else:
return False