栈实现简单括号匹配

 1 #后来的开括号先被闭括号匹配掉,因此栈中仅缓存开括号,后进先出(匹配)
 2 #如果栈空了还有闭括号那错误,如()),否则将“(”踢出栈
 3 
 4 from pythonds import Stack
 5 def parChecker(symbolString):
 6     s = Stack()
 7     balanced = True #定义一个布尔变量
 8     index = 0
 9     while index < len(symbolString) and balanced:
10         symbol = symbolString[index]  #index:元素索引序号
11         if symbol == "(":
12             s.push(symbol)
13         else:
14             if s.isEmpty():
15                 balanced = False
16             else:
17                 s.pop()
18         index = index + 1
19     if balanced and s.isEmpty():
20         return True
21     else:
22         return False

 

posted @ 2018-10-11 16:22  Parallax  阅读(90)  评论(0编辑  收藏  举报