LeetCode 题解工作台

使括号有效的最少添加

只有满足下面几点之一,括号字符串才是有效的: 它是一个空字符串,或者 它可以被写成 AB ( A 与 B 连接), 其中 A 和 B 都是有效字符串,或者 它可以被写作 (A) ,其中 A 是有效字符串。 给定一个括号字符串 s ,在每一次操作中,你都可以在字符串的任何位置插入一个括号 例如,如果 …

category

3

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 栈·状态

bolt

答案摘要

这个问题属于经典的括号匹配问题,可以使用“贪心 + 栈”来解决。 遍历字符串 的每个字符 :

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 栈·状态 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

只有满足下面几点之一,括号字符串才是有效的:

  • 它是一个空字符串,或者
  • 它可以被写成 AB (A 与 B 连接), 其中 A 和 B 都是有效字符串,或者
  • 它可以被写作 (A),其中 A 是有效字符串。

给定一个括号字符串 s ,在每一次操作中,你都可以在字符串的任何位置插入一个括号

  • 例如,如果 s = "()))" ,你可以插入一个开始括号为 "(()))" 或结束括号为 "())))"

返回 为使结果字符串 s 有效而必须添加的最少括号数

 

示例 1:

输入:s = "())"
输出:1

示例 2:

输入:s = "((("
输出:3

 

提示:

  • 1 <= s.length <= 1000
  • s 只包含 '(' 和 ')' 字符。
lightbulb

解题思路

方法一:贪心 + 栈

这个问题属于经典的括号匹配问题,可以使用“贪心 + 栈”来解决。

遍历字符串 ss 的每个字符 cc

  • cc 为左括号,直接将 cc 入栈;
  • cc 为右括号,此时如果栈不为空,且栈顶元素为左括号,则将栈顶元素出栈,表示匹配成功;否则将 cc 入栈。

遍历结束后,栈中剩余的元素个数即为需要添加的括号数。

时间复杂度为 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 为字符串 ss 的长度。

1
2
3
4
5
6
7
8
9
10
class Solution:
    def minAddToMakeValid(self, s: str) -> int:
        stk = []
        for c in s:
            if c == ')' and stk and stk[-1] == '(':
                stk.pop()
            else:
                stk.append(c)
        return len(stk)
speed

复杂度分析

指标
时间complexity is O(N) as each character is visited once. Space complexity is O(1) because only counters are maintained instead of an actual stack, making it optimal for large strings.
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    Check if candidate handles both excess '(' and ')' correctly.

  • question_mark

    Listen for discussion of O(1) space using counters versus explicit stack.

  • question_mark

    Evaluate understanding of stack-based state tracking applied greedily.

warning

常见陷阱

外企场景
  • error

    Failing to count unmatched ')' during iteration leading to undercounted insertions.

  • error

    Using a full stack unnecessarily, increasing space usage.

  • error

    Ignoring leftover '(' at the end of the string.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Compute minimum removals instead of insertions to make a parentheses string valid.

  • arrow_right_alt

    Apply the same stack-based method to strings containing other types of brackets.

  • arrow_right_alt

    Return the corrected valid string after minimal insertions rather than just the count.

help

常见问题

外企场景

使括号有效的最少添加题解:栈·状态 | LeetCode #921 中等