LeetCode 题解工作台

括号的最大嵌套深度

给定 有效括号字符串 s ,返回 s 的 嵌套深度 。嵌套深度是嵌套括号的 最大 数量。 示例 1: 输入: s = "(1+(2*3)+(( 8 )/4))+1" 输出: 3 解释: 数字 8 在嵌套的 3 层括号中。 示例 2: 输入: s = "(1)+((2))+((( 3 )))" 输出:…

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 栈·状态

bolt

答案摘要

我们用一个变量 记录当前的深度,初始时 $d = 0$。 遍历字符串 ,当遇到左括号时,深度 加一,同时更新答案为当前深度 和答案的最大值。当遇到右括号时,深度 减一。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给定 有效括号字符串 s,返回 s嵌套深度。嵌套深度是嵌套括号的 最大 数量。

 

示例 1:

输入:s = "(1+(2*3)+((8)/4))+1"

输出:3

解释:数字 8 在嵌套的 3 层括号中。

示例 2:

输入:s = "(1)+((2))+(((3)))"

输出:3

解释:数字 3 在嵌套的 3 层括号中。

示例 3:

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

输出:3

 

提示:

  • 1 <= s.length <= 100
  • s 由数字 0-9 和字符 '+''-''*''/''('')' 组成
  • 题目数据保证括号字符串 s有效的括号字符串
lightbulb

解题思路

方法一:遍历

我们用一个变量 dd 记录当前的深度,初始时 d=0d = 0

遍历字符串 ss,当遇到左括号时,深度 dd 加一,同时更新答案为当前深度 dd 和答案的最大值。当遇到右括号时,深度 dd 减一。

最后返回答案即可。

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

1
2
3
4
5
6
7
8
9
10
11
class Solution:
    def maxDepth(self, s: str) -> int:
        ans = d = 0
        for c in s:
            if c == '(':
                d += 1
                ans = max(ans, d)
            elif c == ')':
                d -= 1
        return ans
speed

复杂度分析

指标
时间O(N)
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    Check for the candidate's ability to implement a simple stack-based approach.

  • question_mark

    Assess whether the candidate correctly manages nested depths during the traversal.

  • question_mark

    Evaluate the candidate's understanding of time and space complexity optimizations.

warning

常见陷阱

外企场景
  • error

    Failing to properly track the maximum depth during traversal.

  • error

    Incorrectly managing the depth counters, such as failing to update `maxDepth` when necessary.

  • error

    Overcomplicating the solution with unnecessary data structures when a simple stack-based approach suffices.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Consider adding invalid parentheses in the string to check for error handling.

  • arrow_right_alt

    Introduce additional operators and operands to test how the candidate manages complex expressions with nested parentheses.

  • arrow_right_alt

    Test with edge cases such as strings with a single pair of parentheses or no parentheses at all.

help

常见问题

外企场景

括号的最大嵌套深度题解:栈·状态 | LeetCode #1614 简单