pygorithm/stack/parentheses.py

28 lines
674 B
Python
Raw Permalink Normal View History

2023-11-29 19:31:30 +08:00
"""
测试括号是否匹配
1. 左括号数必须与右括号数匹配
2. 从左到右匹配用栈保存每个左括号
3. 每遇到一个右括号则左括号执行出栈操作
4. 匹配成功结束时若栈空则
5. 匹配失败栈未空 > 或者在结束之前栈已空 >
"""
from .stack import Stack
def par_match(parentheses: str) -> bool:
stack = Stack[str]()
for i in parentheses:
if i == '(':
stack.push(i)
elif i == ')':
if stack.is_empty():
return False
stack.pop()
if stack.is_empty():
return True
else:
return False