本文實(shí)例講述了Python實(shí)現(xiàn)的括號(hào)匹配判斷功能。分享給大家供大家參考,具體如下:
1.用一個(gè)棧【python中可以用List】就可以解決,時(shí)間和空間復(fù)雜度都是O(n)
# -*- coding: utf8 -*-# 符號(hào)表SYMBOLS = {'}': '{', ']': '[', ')': '(', '>': '<'}SYMBOLS_L, SYMBOLS_R = SYMBOLS.values(), SYMBOLS.keys()def check(s): arr = [] for c in s: if c in SYMBOLS_L: # 左符號(hào)入棧 arr.append(c) elif c in SYMBOLS_R: # 右符號(hào)要么出棧,要么匹配失敗 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}]"))運(yùn)行結(jié)果:
True
False
2.
# -*- coding: utf8 -*-# 存儲(chǔ)左括號(hào)和右括號(hào)open_brackets = '([{<'close_brackets = ')]}>'# 映射左右括號(hào)便于出棧判斷brackets_map = {')': '(', ']': '[', '}': '{', '>': '<'}# 對(duì)于每一行數(shù)據(jù),進(jìn)行如下判定若括號(hào)為左括號(hào),加入棧,若括號(hào)為右括號(hào),判斷是否跟棧尾括號(hào)對(duì)應(yīng),# 若對(duì)應(yīng),彈出棧尾元素,若所有括號(hào)均正確閉合,則最后棧為空。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)運(yùn)行結(jié)果:
False
True
False
True
3.
在長(zhǎng)度很大的時(shí)候可以盡快判斷一些比較明顯的錯(cuò)誤的模式,節(jié)省時(shí)間:
主要的思路:
首先設(shè)置兩個(gè)列表分別存放的是各種括號(hào)的開括號(hào)和閉括號(hào),然后遍歷給定的字符串,分如下幾種情況:
#!usr/bin/env python# encoding:utf-8def bracket_mathch(one_str): ''''' 括號(hào)匹配 ''' 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, '錯(cuò)誤') tmp = '{}[{()()[]<{{[[[[(())()()(){}[]{}[]()<>]]]]}}>}]' print(bracket_mathch(tmp))運(yùn)行結(jié)果:
('({})', '/xe6/xad/xa3/xe7/xa1/xae')
('({[</xe3/x80/x8a/xe3/x80/x8b>]})', '/xe6/xad/xa3/xe7/xa1/xae')
('[(]){}', '/xe9/x94/x99/xe8/xaf/xaf')
('{{{{{{', '/xe9/x94/x99/xe8/xaf/xaf')
('([{}])', '/xe6/xad/xa3/xe7/xa1/xae')
('}{[()]', '/xe9/x94/x99/xe8/xaf/xaf')
True
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選