LSGO——LeetCode实战(栈系列):20题 有效括号(Valid Parentheses)

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

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。

解法一:(栈)

如果此时我们遍历的字符是括号的左半部分,那么将字符入栈,如果栈顶元素和此时遍历的元素正好组合成一个括号,则出栈。

最后如果栈为空则返回True,反之,返回False。

写法一:

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        ans = []
        if s =="":
            return True
        for i in range(0,len(s)):
            if ans != []:
                if ans[-1] == '(' and s[i] == ")":
                    ans.pop()
                    continue
                elif ans[-1] == '{' and s[i] == "}":
                    ans.pop()
                    continue
                elif ans[-1] == '[' and s[i] == "]":
                    ans.pop()
                    continue
            ans.append(s[i]) 
        if ans == []:
            return True
        else:
            return False

写法二:

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        ans  = []
        mapping ={")":"(","}":"{","]":"["}  #创建字典
        for char in s:
            if char in mapping:
                top_element = ans.pop() if stack  else '#'
                if mapping[char] != top_element:
                    return False
        return not ans   

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值