28 lines
674 B
Python
28 lines
674 B
Python
"""
|
|
测试括号是否匹配:
|
|
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
|