每日一题: 有效括号

面对这个括号匹配的问题,我开始也有点迷茫,隐约觉得可以用栈(Stack)来解决。一起先来看看原题吧:

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

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Every close bracket has a corresponding open bracket of the same type.
 

Example 1:

Input: s = "()"
Output: true
Example 2:

Input: s = "()[]{}"
Output: true
Example 3:

Input: s = "(]"
Output: false
 

Constraints:

1 <= s.length <= 104
s consists of parentheses only '()[]{}'.

当成一个数学问题来看,先找出规则规律,如果先来一个关闭类型的括号(如),], }),那么直接就算false了,如果开和闭合没有成对出现,也会是false。我们可以拿一个Stack来保存open bracket,当循环的当前的字符是open bracket就push到stack。

当当前的字符是closed bracket则弹出顶部Stack的元素,看是否是对应的open bracket,如果是就继续循环,如果不是则返回false。

还要考虑一些边界情况,如果在弹出元素的时候刚好stack为空了,也说明没有配套的open bracket了,也应该返回false。

用Python实现的代码如下,非常清晰:

复制代码
class Solution:
    def isValid(self, s: str) -> bool:
        bracketMap = {
            "(": ")",
            "{": "}",
            "[": "]"
        }

        stack = []

        for char in s:
            if char in bracketMap:
                # push the open bracket into the stack
                stack.append(char)
            else:
                # If the stack is empty or do not have the matching open bracket, it means the closed bracket does not have the related open bracket
                if len(stack) == 0 or bracketMap[stack.pop()] != char:
                    return False

        return len(stack) == 0
相关推荐
Tisfy1 天前
LeetCode 2540.最小公共值:双指针(O(m+n))
算法·leetcode·题解·双指针
运筹vivo@1 天前
LeetCode 2405. 子字符串的最优划分
c++·算法·leetcode·职场和发展·哈希表
sheeta19982 天前
LeetCode 每日一题笔记 日期:2026.05.19 题目:2540. 最小公共值
笔记·leetcode·排序算法
sheeta19982 天前
LeetCode 每日一题笔记 日期:2026.05.16 题目:154. 寻找旋转排序数组中的最小值 II
笔记·算法·leetcode
阿Y加油吧2 天前
两道位运算 / 摩尔投票经典题复盘:只出现一次的数字 & 多数元素
数据结构·算法·leetcode
承渊政道2 天前
【贪心算法】(经典实战应用解析(五):单调递增的数字、坏了的计算器、合并区间、⽆重叠区间、⽤最少数量的箭引爆⽓球)
数据结构·c++·leetcode·贪心算法·排序算法·动态规划·哈希算法
人道领域2 天前
【LeetCode刷题日记】106.从遍历序列重建二叉树:手撕递归边界,彻底搞懂左闭右闭 vs 左闭右开
java·算法·leetcode
运筹vivo@2 天前
LeetCode 2540. 最小公共值
算法·leetcode·职场和发展
sheeta19982 天前
LeetCode 每日一题笔记 日期:2026.05.15 题目:153. 寻找旋转排序数组中的最小值
笔记·算法·leetcode
我爱cope2 天前
【力扣hot100:239. 滑动窗口最大值】
算法·leetcode·职场和发展