检查括号是否闭合 python实现
栈应用之 括号匹配问题(Python 版)
检查括号是否闭合
- 循序扫描被检查正文(一个字符)里的一个个字符
- 检查中跳过无关字符(所有非括号字符都与当前处理无关)
- 遇到开括号将其压入栈
- 遇到闭括号时弹出当时的栈顶元素与之匹配
- 如果匹配成功则继续,发现匹配失败时则以检查失败结束
1 def check_parens(text) :
2 # 括号匹配检查函数,text 是被检查的正文串
3 parens = "(){}[]"
4 open_parens = "({["
5 opposite = {")":"(", "}":"{", "]":"["}
6
7 def parentheses(text) :
8 # 括号生成器,每次调用返回text里的下一括号及其位置
9 i.text_len = 0,len(text)
10 while True :
11 while i < text_len and text[i] not in parens :
12 i += 1
13 if i >= text_len :
14 return
15 yield text[i],i
16 i += 1
17
18 st = SStack() # 创建栈 st
19
20 for pr , i in parentheses(text) : # 对text里各括号和位置迭代
21 if pr in open_parens : # 开括号,压栈并继续
22 st.push(pr)
23 elif st.pop() != opposite[pr] : # 闭括号 若匹配失败就退出
24 print("Unmatching is found at ",i,"for",pr)
25 return False
26 # else : 匹配成功什么也不做