-
Notifications
You must be signed in to change notification settings - Fork 0
/
括号匹配.py
38 lines (30 loc) · 811 Bytes
/
括号匹配.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from pythonds.basic.stack import Stack
"""
使用pythonds库直接构造栈的对象。
"""
def matches(open, close):
opens = "([{"
closes = ")]}"
return opens.index(open) == close.index(close)
def parChecker(symobolString):
s = Stack()
balanced = True
index = 0
while index < len(symobolString) and balanced:
symbol = symobolString[index]
if symbol == "([{":
s.push(symbol)
else:
if s.isEmpty():
balanced = False
else:
# 删除对应的')'
top = s.pop()
if not matches(top, symbol):
balanced = False
index += 1
if balanced and s.isEmpty():
return True
else:
return False
print(parChecker("(()))"))