LeetCode 题解工作台
括号的最大嵌套深度
给定 有效括号字符串 s ,返回 s 的 嵌套深度 。嵌套深度是嵌套括号的 最大 数量。 示例 1: 输入: s = "(1+(2*3)+(( 8 )/4))+1" 输出: 3 解释: 数字 8 在嵌套的 3 层括号中。 示例 2: 输入: s = "(1)+((2))+((( 3 )))" 输出:…
2
题型
7
代码语言
3
相关题
当前训练重点
简单 · 栈·状态
答案摘要
我们用一个变量 记录当前的深度,初始时 $d = 0$。 遍历字符串 ,当遇到左括号时,深度 加一,同时更新答案为当前深度 和答案的最大值。当遇到右括号时,深度 减一。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 栈·状态 题型思路
题目描述
给定 有效括号字符串 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 <= 100s由数字0-9和字符'+'、'-'、'*'、'/'、'('、')'组成- 题目数据保证括号字符串
s是 有效的括号字符串
解题思路
方法一:遍历
我们用一个变量 记录当前的深度,初始时 。
遍历字符串 ,当遇到左括号时,深度 加一,同时更新答案为当前深度 和答案的最大值。当遇到右括号时,深度 减一。
最后返回答案即可。
时间复杂度 ,其中 是字符串 的长度。空间复杂度 。
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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(N) |
| 空间 | O(1) |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.