⚡Flashcard Drill➔
NeetCode #345LC-20EasyStackBlind 75NC 150NC 250
← Back to All Problems

#345 · #20 · Valid Parentheses(有效的括号)

📌 Problem Statement & Constraints

Given a string s containing only the characters (, ), {, }, [ and ], determine whether the brackets are correctly matched and nested. Constraints: 1 <= s.length <= 10^4.

💡 Core Algorithmic Approaches

  1. A stack is the natural structure: opening brackets are pushed, and a closing bracket must match the most recent unmatched opening bracket.
  2. Map each closing bracket to its opening partner so the check is a single dictionary lookup.
  3. If the stack is empty when a closing bracket arrives, or the top does not match, the string is invalid.
  4. At the end, the stack must be empty -- any leftover opening bracket is unmatched.

💻 Benchmark Python3 Implementation

class Solution:
    def isValid(self, s: str) -> bool:
        pairs = {")": "(", "]": "[", "}": "{"}
        st = []
        for ch in s:
            if ch in pairs:                # closing bracket
                if not st or st.pop() != pairs[ch]:
                    return False
            else:                          # opening bracket
                st.append(ch)
        return not st                      # no unmatched openings left

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): each character is pushed or popped at most once.
💾 Space Complexity
O(n) for the stack in the worst case (a string of all opening brackets).

⚠️ Interview Pitfalls & Follow-ups

  • Forgetting the final emptiness check: "(((" would be wrongly accepted.
  • Popping before checking for an empty stack: st.pop() on an empty list raises IndexError; the not st guard must come first.
  • Matching by bracket type rather than by pairing: "(]" would pass if you only compared the opening characters loosely.
  • Recursing on nested brackets: the stack handles arbitrary nesting with no recursion depth concerns.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Stack Problems

中文速览与面试要点

有效的括号

给定一个只包括 ( 、 ) 、 、 、 [ 、 ] 的字符串 s,判断字符串是否有效。有效字符串需满足:① 左括号必须用相同类型的右括号闭合;② 左括号必须以正确的顺序闭合;③ 每个右括号都有一个对应的相同类型的左括号。约束:1 ≤ s.length ≤ 10^4;s 仅由括号 ()[] 组成。

核心要点

  • 栈 + 映射表(标准解) :遇到左括号入栈;遇到右括号则检查栈顶是否为对应的左括号——是则弹出,否则返回 False。
  • 为什么用栈 :括号匹配是「后进先出」的典型场景——最近未闭合的左括号必须先被闭合。
  • 收尾判定 :遍历结束后栈必须为空,否则说明有未闭合的左括号。
  • 映射表的方向 :把「右括号 → 左括号」作为键值对,这样遇到右括号时只需一次查表即可得到期望的栈顶。

常见陷阱

  • 忘记检查 not stack :遇到右括号而栈为空时直接 stack.pop() 会抛 IndexError。
  • 映射表方向写反 :若把「左括号 → 右括号」作为键,遇到右括号时无法直接查表,需要额外判断。
  • 收尾忘记检查栈空 :如 "(((" 会错误返回 True。
  • 只统计左右括号数量是否相等 :无法判断顺序,如 ")(" 数量相等但不合法。

参考实现

class Solution:
    def isValid(self, s: str) -> bool:
        pairs = {')': '(', ']': '[', '}': '{'}
        stack = []
        for c in s:
            if c in pairs:                      # 右括号
                if not stack or stack.pop() != pairs[c]:
                    return False
            else:                               # 左括号
                stack.append(c)
        return not stack                        # 全部闭合则栈为空