LeetCode-20 valid parenthesis

本文介绍了一种使用栈解决括号匹配问题的有效方法。通过构建一个包含括号对应关系的字典,并遍历输入字符串来判断括号是否正确配对。文章详细解释了算法的工作原理及其实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:括号匹配问题

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

解题:

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

class Solution:
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        """
        根据tag给的提示,应该是用到了stack的思想
        构建一个字典,将右括号放在keys,左括号放在values
        如果s中的元素在values中,压栈append
        如果在keys中:栈为空或没有匹配的左括号,false
        其他情况false
        最终栈应该是空的,都对应的pop掉了
        """
        dict = {'}':'{',']':'[',')':'('}
        stack = []
        for ch in s:
            if ch in dict.values():
                stack.append(ch)
            elif ch in dict.keys():
                if stack == [] or dict[ch] != stack.pop():
                    return False
            else:
                return False
        return stack == []

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值