日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

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

欄目分類
最近更新