大致思想是:
(1)定义属性,如括号以及括号的配对关系
(2)从字符串(文本)中提取括号(此处以字符串为例),从而得到一个只包含括号的字符串
(3)利用栈存储开括号,遇到闭括号就与栈顶元素进行配对(此处直接将list当做栈使用),若配对就出栈
class ParenMatch(object): """括号匹配问题""" def __init__(self, text): self.parens = "(){}[]" self.opposite = {"(":")", "{":"}", "[":"]"} self.text = text def generate_paren(self): """括号生成器,每次调用返回text里的下一括号及其位置""" i, text_len = 0, len(self.text) while True: while i < text_len and self.text[i] not in self.parens: i += 1 if i >= text_len: return yield self.text[i], i i += 1 def handle_match(self): """处理括号匹配问题""" stack = [] for pr, i in self.generate_paren(): if pr in self.opposite: stack.append(pr) elif stack and self.opposite[stack[-1]] == pr: stack.pop()else: print("Unmatching is found at", i, "for", pr) return False return not stack text = "[(哈哈{})]" pm = ParenMatch(text) print(pm.handle_match())