导包:
from pythonds.basic.stack import Stack
匹配“(){{}}[]”
不匹配“{](}”“{{{{}”
from pythonds.basic.stack import Stack
def parChecker(symbolString):
s = Stack()
ok = True
index = 0
while index < len(symbolString) and ok:
x = symbolString[index]
if x in "([{":
s.push(x)
else:
if s.isEmpty():
ok=False#单个右括号,直接退出
else:
top=s.pop()#压出栈顶的左括号
if not matches(top,x):
ok=False
index = index + 1
if ok and s.isEmpty():
return True
else:
return False
def matches(left,right):
lefts="([{"
rights=")]}"
return lefts.index(left)==rights.index(right)#用index函数返回左右括号的位置是否匹配
print(parChecker("(((()))"))
print(parChecker("{{}}[][]()"))