python 【栈】判断括号匹配问题

单一括号匹配

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值