(python)小菜狗算法日记(辅助栈系列)_leetcode 20. 有效的括号

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

有效字符串需满足:

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

示例 1:

输入: "()"
输出: true
示例 2:

输入: "()[]{}"
输出: true
示例 3:

输入: "(]"
输出: false
示例 4:

输入: "([)]"
输出: false
示例 5:

输入: "{[]}"
输出: true

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses

把对应的括号存到字典里,用一个辅助栈帮助处理,遇到一对就弹出。最后判断辅助栈剩余是否为空。

今天发现 for c in dic这个遍历字典只找了键,我以前还是写的 for c in dic.keys()

class Solution:
    def isValid(self, s: str) -> bool:
        dic = {'(':')','[':']','{':'}','?':'?'}  #多存一个问号为了下面栈里存的问号在dic[stack.pop()]时不报错
        stack=['?']   #多存一个问号为了避免stack.pop()报错
        for ss in s:
            if ss in dic:
                stack.append(ss)
            elif dic[stack.pop()]!=ss:
                return False
        return len(stack)==1 #最后剩初始那个问号

代码来源:作者:jyd 链接:https://leetcode-cn.com/problems/valid-parentheses/solution/valid-parentheses-fu-zhu-zhan-fa-by-jin407891080/

直接这样写的话就不用在字典里存{'?':'?'}了

class Solution:
    def isValid(self, s: str) -> bool:
        dic = {'(':')','[':']','{':'}'}
        stack = ['?']
        for ss in s:
            if ss in dic:
                stack.append(dic[ss])
            elif ss!=stack.pop():
                return False
        return len(stack)==1

把字典反过来存的话,if else也反一下:

class Solution:
    def isValid(self, s: str) -> bool:
        dic = {']':'[','}':'{',')':'(','?':'?'}
        stack = ['?']
        for c in s:
            if c in dic:
                if stack[-1]!=dic[c]:
                    return False
                else:
                    stack.pop()
            else:
                stack.append(c)
        return len(stack)==1

官方解答就是反过来的,不过stack.pop()加了个判断stack是否为空,就不用那个初始问号了。

class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        mapping = {")": "(", "}": "{", "]": "["}
        for char in s:
            if char in mapping:
                top_element = stack.pop() if stack else '#'
                if mapping[char] != top_element:
                    return False
            else:
                stack.append(char)
        return not stack

作者:LeetCode 链接:https://leetcode-cn.com/problems/valid-parentheses/solution/you-xiao-de-gua-hao-by-leetcode/
来源:力扣(LeetCode)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值