每日一题: 有效括号

面对这个括号匹配的问题,我开始也有点迷茫,隐约觉得可以用栈(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
相关推荐
练习时长一年1 小时前
LeetCode热题100(分割等和子集)
算法·leetcode·职场和发展
52Hz1181 小时前
力扣148.排序链表
leetcode
iAkuya1 小时前
(leetcode)力扣100 46二叉树展开为链表(递归||迭代||右子树的前置节点)
windows·leetcode·链表
程序员-King.2 小时前
day151—双端队列—找树左下角的值(LeetCode-513)
算法·leetcode·二叉树·双端队列·队列
苦藤新鸡2 小时前
15 .数组右移动k个单位
算法·leetcode·动态规划·力扣
氷泠3 小时前
路径总和系列(LeetCode 112 & 113 & 437 & 666)
leetcode·前缀和·深度优先·路径总和
橘颂TA3 小时前
【剑斩OFFER】算法的暴力美学——力扣 130 题:被围绕的区域
算法·leetcode·职场和发展·结构与算法
一分之二~3 小时前
回溯算法--解数独
开发语言·数据结构·c++·算法·leetcode
程序员-King.4 小时前
day154—回溯—分割回文串(LeetCode-131)
算法·leetcode·深度优先·回溯
程序员-King.4 小时前
day155—回溯—组合(LeetCode-77)
算法·leetcode·回溯