【发布时间】:2018-04-23 04:12:21
【问题描述】:
我一直在尝试用python做一个平衡符号问题
import Stack from Stack
def parChecker(symbolString):
s = Stack()
balanced = True
index = 0
while index < len(symbolString) and balanced:
symbol = symbolString[index]
if symbol in "([{":
s.push(symbol)
else:
if s.isEmpty():
balanced = False
else:
top = s.pop()
if not matches(top,symbol):
balanced = False
index = index + 1
if balanced and s.isEmpty():
return True
else:
return False
def matches(open,close):
opens = "([{"
closers = ")]}"
return opens.index(open) == closers.index(close)
print(parChecker('{{([][])}()}'))
print(parChecker('[{()]'))
print (parChecker('({[})]') # --- THis is balanced but returns false
但这会对输入 ([{)}] 返回 false。这个输入似乎是平衡的,但返回的输出是假的。
【问题讨论】: