————————————————————
#封装一个栈类
class Stack:
def __init__(self):
self.stack = []
def push(self , element):#进栈
self.stack.append(element)
def pop(self):#出栈
return self.stack.pop()
def get_pop(self):
if len(self.stack)>0:
return self.stack[-1]
else:
return None
def is_empty(self):
return len(self.stack)==0
#测试
stack = Stack()
for i in range(5):
stack.push(i)
print(stack.pop()) #后进先出 lifo
#应用:括号匹配问题
def brace_match(s):
'''
:param s: var 输入字符串
:return:
'''
match = {']':'[',')':'(','}':'{'}
stack = Stack()
for ch in s:
if ch in {'(','{','['}:
stack.push(ch)
else:#ch 是右边括号
if stack.get_pop() == match[ch]:
stack.pop()
elif stack.is_empty():
return False
else: #ch既不匹配左括号也不为空
return False
if stack.is_empty():
return True
else:
return False
#测试
print(brace_match('[]{{([}])}}'))
print(brace_match('({{{}}[()]})'))