Show problems as
Classic problem #1614EasyStringStackBracket Sequences

Maximum Nesting Depth of the Parentheses

Real-world version: Deepest Bracket Layer
Tracked in this browser only
Read Maximum Nesting Depth of the Parentheses on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A control panel writes each logged formula as a string line built from the digits 0 to 9 and the characters +, -, *, /, ( and ).

The brackets in line always pair up: reading left to right, a ) never appears before its partner, and every ( is closed before the line ends. The panel makes no promise about the arithmetic itself, so apart from the brackets a line may read oddly.

Every bracket pair in line sits inside some number of other bracket pairs. Call one more than that number the pair's layer, so a pair nested inside nothing is on layer 1.

Return the largest layer reached by any bracket pair in line, and 0 when line has no brackets at all.

Examples

Example 1

Input
line = "7+((5-2)*3)"
Output
2

The outer pair wrapping `(5-2)*3` sits inside nothing, so it is on layer 1, and the pair around `5-2` sits inside it on layer 2.

Example 2

Input
line = "4*5-6"
Output
0

No brackets appear anywhere in the line.

Example 3

Input
line = "((9))+(8)"
Output
2

The pair around `9` sits inside one other pair, putting it on layer 2. The pair around `8` sits inside nothing, so it is only on layer 1.

Example 4

Input
line = "(2+(3)*(4+(5)))"
Output
3

The pair around `5` sits inside the pair around `4+(5)`, which sits inside the outermost pair, so that innermost pair is on layer 3. The pair around `3` reaches only layer 2.

Example 5

Input
line = "(6)"
Output
1

One pair, sitting inside nothing, so its layer is 1.

Constraints

  • 1 <= line.length <= 100
  • line consists of digits 0-9 and the characters '+', '-', '*', '/', '(' and ')'.
  • The brackets of line are guaranteed to pair up correctly.

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def max_depth(line: str) -> int:
Java
public int maxDepth(String line)