单一括号匹配
from pythonds.basic import Stack
def parChecker(symbolString):
s=Stack()
balanced=True
index=0
while index<len(symbolString) and balanced:
symbol=symbolString[index]
if symbol=="(": # 如果是左括号,就压入栈
s.push(symbol)
else: # 如果是右括号
if s.isEmpty(): # 当s为空时,说明里面不存在与之相匹配的左括号,所以balanced=False
balanced=False
else: # 当s不为空时,s就弹出top元素,这个元素必然为左括号
s.pop()
index=index+1
if balanced and s.isEmpty(): # balanced=True,而s.isEmpty()为False,这种情况出现在s中都是左括号的情况
return True
else:
return False
print(parChecker('((()))'))
print(parChecker('(()'))
True
False
更通用的括号匹配
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('[{()]'))
True
False
参考:
python实现栈Stack
pythonds
https://runestone.academy/runestone/static/pythonds/BasicDS/SimpleBalancedParentheses.html
https://runestone.academy/runestone/static/pythonds/BasicDS/BalancedSymbols(AGeneralCase).html