学无先后,达者为师

网站首页 编程语言 正文

python:实现balanced parentheses平衡括号表达式算法(附完整源码)

作者:全栈技术博客 更新时间: 2022-07-21 编程语言

python:实现balanced parentheses平衡括号表达式算法

from .stack import Stack
def balanced_parentheses(parentheses: str) -> bool:
    stack: Stack[str] = Stack()
    bracket_pairs = {"(": ")", "[": "]", "{": "}"}
    for bracket in parentheses:
        if bracket in bracket_pairs:
            stack.push(bracket)
        elif bracket in (")", "]", "}"):
            if stack.is_empty() or bracket_pairs[stack.pop()] != bracket:
                return False
    return stack.is_empty()


if __name__ == "__main__":
    from doctest import testmod

    testmod()

    examples = ["((()))", "((())", "(()))"]
    print("Balanced parentheses demonstration:\n")
    for example in examples:
        not_str = "" if balanced_parentheses(example) else "not "
        print(f"{example} is {not_str}balanced")

原文链接:https://blog.csdn.net/it_xiangqiang/article/details/125898454

栏目分类
最近更新