栈应用之 括号匹配问题(Python 版)
2021-07-09 02:04
                         标签:匹配   括号匹配   not   opp   ret   字符   code   false   osi    检查括号是否闭合 栈应用之 括号匹配问题(Python 版) 标签:匹配   括号匹配   not   opp   ret   字符   code   false   osi    原文地址:https://www.cnblogs.com/zlsgh/p/9579941.html栈应用之 括号匹配问题(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 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 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 :  # 匹配成功什么也不做
27             
文章标题:栈应用之 括号匹配问题(Python 版)
文章链接:http://soscw.com/index.php/essay/102564.html