1. 程式人生 > >棧應用之 括號匹配問題(Python 版)

棧應用之 括號匹配問題(Python 版)

text 所有 != parent else 括號 check style pan

棧應用之 括號匹配問題(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 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 版)