本文实例讲述了Python实现的括号匹配判断功能。分享给大家供大家参考,具体如下:
1.用一个栈【python中可以用List】就可以解决,时间和空间复杂度都是O(n)
# -*- coding: utf8 -*-# 符号表SYMBOLS = {'}': '{', ']': '[', ')': '(', '>': '<'}SYMBOLS_L, SYMBOLS_R = SYMBOLS.values(), SYMBOLS.keys()def check(s): arr = [] for c in s: if c in SYMBOLS_L: # 左符号入栈 arr.append(c) elif c in SYMBOLS_R: # 右符号要么出栈,要么匹配失败 if arr and arr[-1] == SYMBOLS[c]: arr.pop() else: return False return Trueprint(check("3 * {3 +[(2 -3) * (4+5)]}"))print(check("3 * {3+ [4 - 6}]"))
运行结果:
True
False
2.
# -*- coding: utf8 -*-# 存储左括号和右括号open_brackets = '([{<'close_brackets = ')]}>'# 映射左右括号便于出栈判断brackets_map = {')': '(', ']': '[', '}': '{', '>': '<'}# 对于每一行数据,进行如下判定若括号为左括号,加入栈,若括号为右括号,判断是否跟栈尾括号对应,# 若对应,弹出栈尾元素,若所有括号均正确闭合,则最后栈为空。rows = ['([<^>x[ ]{a}]{/}{t}g<^>)<{x}b>{x}<z({%}w >[b][c[c]]{<h>{h}}', '[/]{((x)({{*}*}w)w){f}{v}[%(^[z]{u}{ })([[ ]-]h)]{c}(*)[y]}', '<<(^)z>>[b]< >[[(c)u[v]{z<b< >><b>}]g][/b[(])v(v)(+)](v)', '[[b]][(v)g]<z>([{{<->+}e}[*]d<+>]g[[a] <+>(v){b}<e>]){a}[u]']for row in rows: stack = [] label = True for char in row: if char in open_brackets: stack.append(char) elif char in close_brackets: if len(stack) < 1: label = False break elif brackets_map[char] == stack[-1]: stack.pop() else: label = False break else: continue if stack != []: label = False print(label)
运行结果:
False
True
False
True
3.
在长度很大的时候可以尽快判断一些比较明显的错误的模式,节省时间:
主要的思路:
首先设置两个列表分别存放的是各种括号的开括号和闭括号,然后遍历给定的字符串,分如下几种情况:
#!usr/bin/env python# encoding:utf-8def bracket_mathch(one_str): ''''' 括号匹配 ''' tmp_list = [] open_bracket_list = ['(', '[', '{', '<', '《'] close_bracket_list = [')', ']', '}', '>', '》'] one_str_list = list(one_str) length = len(one_str_list) set_list = list(set(one_str_list)) num_list = [one_str_list.count(one) for one in set_list] if one_str[0] in close_bracket_list: return False elif length % 2 != 0: return False elif len(set_list) % 2 != 0: return False else: for i in range(length): if one_str[i] in open_bracket_list: tmp_list.append(one_str[i]) elif one_str[i] in close_bracket_list: if close_bracket_list.index(one_str[i]) == open_bracket_list.index(tmp_list[-1]): tmp_list.pop() else: return False break return Trueif __name__ == '__main__': one_str_list = ['({})', '({[<《》>]})', '[(]){}', '{{{{{{', '([{}])', '}{[()]'] for one_str in one_str_list: if bracket_mathch(one_str): print(one_str, '正确') else: print(one_str, '错误') tmp = '{}[{()()[]<{{[[[[(())()()(){}[]{}[]()<>]]]]}}>}]' print(bracket_mathch(tmp))
新闻热点
疑难解答