# 栈(后进先出)第一个元素是栈底,最后一个是栈顶
# 栈的基本操作:1、进栈(push)li.append 2、出栈(pop)li.pop 3、取栈顶(gettop)li[-1]
class Stack:
def __init__(self):
self.stack = []
def push(self, element):
self.stack.append(element)
def pop(self):
if len(self.stack) > 0:
return self.stack.pop()
else:
return None
def get_top(self):
if len(self.stack) > 0:
return self.stack[-1]
else:
return None
def is_empty(self):
return len(self.stack) == 0
# stack = Stack()
# stack.push(1)
# stack.push(2)
# stack.push(3)
# print(stack.pop())
# 括号匹配
def brace_match(s):
match = {'}': '{', ']': '[', ')': '('}
stack = Stack()
for ch in s:
if ch in {'(', '[', '{'}:
stack.push(ch)
elif stack.is_empty():
return False
elif stack.get_top() == match[ch]:
stack.pop()
else:
return False
if stack.is_empty():
return True
else:
return False
print(brace_match('[{()}]'))
print(brace_match('[{(}'))
print(brace_match('[{()}'))
栈的基本操作和括号匹配问题
最新推荐文章于 2024-08-20 16:20:53 发布