brackets = {'}': '{', ')': '(', ']': '['}
bracketsValues, bracketsKeys = brackets.values(), brackets.keys() # 把键值对的键和值放入list
def is_match(str):
lt = []
for c in str:
if c in bracketsValues:
# 左括号入栈
lt.append(c)
elif c in bracketsKeys:
# 右括号,要么栈顶元素出栈,要么匹配失败
if len(lt) == 0 or lt[-1] != brackets[c]:
return False
lt.pop()
return True
print(is_match(input()))
方式二:看我上一篇文章
Python栈的顺序存储结构,顺序栈类的实现,以及使用栈判断输入括号是否匹配算法_小星博博的博客-CSDN博客废话不多说,直接上代码更多源码分享请关注小星博博Giteehttps://gitee.com/xiaoxingbobo-personal1、首先添加SqStack顺序栈类class SqStack: # 构造函数 def __init__(self): self.data = [] # 声明空列表,作为栈的存放元素 # 判断栈是否为空 def empty(self): if len(self.data) == 0:https://blog.csdn.net/baidu_39105563/article/details/121294726



