括号匹配

Q:给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。有效字符串需满足:

    1、左括号必须用相同类型的右括号闭合。
    2、左括号必须以正确的顺序闭合。

注意:空字符串可被认为是有效字符串。

解法一:利用栈的知识,如果是左括号,入栈;如果是右括号,自爱栈不空的情况下,与栈顶元素比较,如果匹配则出栈。最后判断栈是否为空,如果为空,则全部匹配成功。

class Solution:
    def isValid(self, s: str) -> bool:
        s = s.lstrip(' ').rstrip(' ')
        if s=='':
            return True
        if len(s)%2==1:
            return False
        ls = []
        if s[0]=='}' or s[0]==']' or s[0]==')':
            return False
        else:
            ls.append(s[0])
        for i in range(1,len(s)):
            if s[i] == '(' or s[i] == '[' or s[i] == '{':
                ls.append(s[i])
            if s[i] == ']' and len(ls) != 0:
                if ls[len(ls)-1]=='[':
                    ls.pop()
            elif s[i] == ')' and len(ls) != 0:
                if ls[len(ls)-1]=='(':
                    ls.pop()              
            elif s[i] == '}' and len(ls) != 0:
                if ls[len(ls)-1]=='{':
                    ls.pop()
                
        if len(ls) == 0:
            return True
        else:
            return False

解法二:利用Python中的replace函数

# 括号匹配
# 用replace把成对的括号替换为空
# 如果最后s不为空串,则不匹配

def isValid(s):
    while '{}' in s or '[]' in s or '()' in s:
        s = s.replace('()', '')
        s = s.replace('[]', '')
        s = s.replace('{}', '')
    return len(s) == 0

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值