首页 > 编程语言 > 详细

python---括号匹配

时间:2020-03-28 22:11:02      阅读:69      评论:0      收藏:0      [点我收藏+]
"""
括号匹配

输入: "()[]{}" 输出true
输入:"([)]" 输出false
输入:")(()))" 输出false
输入:"()" 输出true
输入:"((([])))" 输出true
输入:"]][[" 输出false
输入:([)] 输出false
"""


def bracket_match_v1(brackets_str):
    brackets_dict = {‘(‘: ‘)‘, ‘[‘: ‘]‘, ‘{‘: ‘}‘}

    # 右括号开头
    if brackets_str[0] in brackets_dict.values():
        return False

    # 左括号开头
    brackets_stack = []
    for bracket in brackets_str:
        # 左括号进栈
        if bracket in brackets_dict.keys():
            brackets_stack.append(bracket)

        # 右括号 去匹配栈顶元素是否对应
        elif bracket in brackets_dict.values():
            if brackets_dict[brackets_stack.pop()] != bracket:
                return False

    if not brackets_stack:
        return True

    return False


def bracket_match_v2(brackets_str):
    """简化版"""
    brackets_dict = {‘)‘: ‘(‘, ‘]‘: ‘[‘, ‘}‘: ‘{‘}
    brackets_stack = []
    for bracket in brackets_str:
        # 左括号
        if bracket in brackets_dict.values():
            brackets_stack.append(bracket)
        # 右括号, 包含右括号开头
        elif not brackets_stack or brackets_dict[bracket] != brackets_stack.pop():
            return False

    return not brackets_stack


print(bracket_match_v1("()[]{}"))
print(bracket_match_v1("([)]"))
print(bracket_match_v1(")(()))"))
print(bracket_match_v1("()"))
print(bracket_match_v1("((([])))"))
print(bracket_match_v1("]][["))
print(bracket_match_v1("([)]"))

print(‘-‘ * 66)

print(bracket_match_v2("()[]{}"))
print(bracket_match_v2("([)]"))
print(bracket_match_v2(")(()))"))
print(bracket_match_v2("()"))
print(bracket_match_v2("((([])))"))
print(bracket_match_v2("]][["))
print(bracket_match_v2("([)]"))

python---括号匹配

原文:https://www.cnblogs.com/KX-Lau/p/12589626.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!