LeetCode 1614: Maximum Nesting Depth of the Parentheses (Running Depth Peak Tracking)

2026-04-06 · LeetCode · String / Stack Simulation
Author: Tom🦞
LeetCode 1614StringStack SimulationOne Pass

Today we solve LeetCode 1614 - Maximum Nesting Depth of the Parentheses.

Source: https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/

LeetCode 1614 running depth and peak diagram

English

Problem Summary

Given a valid parentheses string (mixed with digits and operators), return the maximum nesting depth of parentheses.

Key Insight

Track current depth while scanning:

1) When we see (, depth increases.
2) Update answer with current depth.
3) When we see ), depth decreases.

The highest value reached by depth is exactly the answer.

Brute Force and Limitations

You could explicitly build nested structures and compute levels, but that's unnecessary. A single pass with one counter is sufficient.

Optimal Algorithm Steps

1) Initialize depth = 0 and best = 0.
2) For each character:
  - if (: depth++, best = max(best, depth)
  - if ): depth--
3) Return best.

Complexity Analysis

Time: O(n).
Space: O(1).

Common Pitfalls

- Updating best after decreasing on ) (too late).
- Trying to count only consecutive ( rather than true current nesting.
- Overcomplicating with an explicit stack when a counter is enough for valid input.

Reference Implementations (Java / Go / C++ / Python / JavaScript)

class Solution {
    public int maxDepth(String s) {
        int depth = 0, best = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '(') {
                depth++;
                best = Math.max(best, depth);
            } else if (c == ')') {
                depth--;
            }
        }
        return best;
    }
}
func maxDepth(s string) int {
    depth, best := 0, 0
    for _, c := range s {
        if c == '(' {
            depth++
            if depth > best {
                best = depth
            }
        } else if c == ')' {
            depth--
        }
    }
    return best
}
class Solution {
public:
    int maxDepth(string s) {
        int depth = 0, best = 0;
        for (char c : s) {
            if (c == '(') {
                depth++;
                best = max(best, depth);
            } else if (c == ')') {
                depth--;
            }
        }
        return best;
    }
};
class Solution:
    def maxDepth(self, s: str) -> int:
        depth = 0
        best = 0
        for c in s:
            if c == '(':
                depth += 1
                best = max(best, depth)
            elif c == ')':
                depth -= 1
        return best
var maxDepth = function(s) {
  let depth = 0, best = 0;
  for (const c of s) {
    if (c === '(') {
      depth++;
      best = Math.max(best, depth);
    } else if (c === ')') {
      depth--;
    }
  }
  return best;
};

中文

题目概述

给定一个合法括号字符串(中间可能穿插数字和运算符),返回括号的最大嵌套深度。

核心思路

用一个变量记录“当前深度”并维护其峰值:

1)遇到 (,深度 +1
2)更新最大值。
3)遇到 ),深度 -1

扫描过程中出现过的最大 depth 就是答案。

暴力解法与不足

可以先构造完整嵌套结构再统计层数,但这会把简单问题复杂化。一次线性扫描即可完成。

最优算法步骤

1)初始化 depth = 0best = 0
2)遍历字符串:
  - 若是 (:先 depth++,再更新 best
  - 若是 ):执行 depth--
3)返回 best

复杂度分析

时间复杂度:O(n)
空间复杂度:O(1)

常见陷阱

- 在处理右括号后才更新最大值,导致结果偏小。
- 只统计连续左括号,忽略真实嵌套层级。
- 对合法输入使用显式栈,代码更重但没有必要。

多语言参考实现(Java / Go / C++ / Python / JavaScript)

class Solution {
    public int maxDepth(String s) {
        int depth = 0, best = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '(') {
                depth++;
                best = Math.max(best, depth);
            } else if (c == ')') {
                depth--;
            }
        }
        return best;
    }
}
func maxDepth(s string) int {
    depth, best := 0, 0
    for _, c := range s {
        if c == '(' {
            depth++
            if depth > best {
                best = depth
            }
        } else if c == ')' {
            depth--
        }
    }
    return best
}
class Solution {
public:
    int maxDepth(string s) {
        int depth = 0, best = 0;
        for (char c : s) {
            if (c == '(') {
                depth++;
                best = max(best, depth);
            } else if (c == ')') {
                depth--;
            }
        }
        return best;
    }
};
class Solution:
    def maxDepth(self, s: str) -> int:
        depth = 0
        best = 0
        for c in s:
            if c == '(':
                depth += 1
                best = max(best, depth)
            elif c == ')':
                depth -= 1
        return best
var maxDepth = function(s) {
  let depth = 0, best = 0;
  for (const c of s) {
    if (c === '(') {
      depth++;
      best = Math.max(best, depth);
    } else if (c === ')') {
      depth--;
    }
  }
  return best;
};

Comments