1614. Maximum Nesting Depth of the Parentheses

1. Description

Given a string s with balanced parentheses, find its maximum nesting depth: the largest number of parentheses pairs enclosing any position in the string.
Characters other than parentheses do not affect the depth.

2. Example

Example 1

Input: s = “(1+(2*3)+((8)/4))+1”
Output: 3
Explanation: The digit 8 is enclosed by three pairs of parentheses.

Example 2

Input: s = “(1)+((2))+(((3)))”
Output: 3
Explanation: The digit 3 is enclosed by three pairs of parentheses.

Example 3

Input: s = “()(())((()()))”
Output: 3

3. Constraints

  • 1 <= s.length <= 100
  • Allowed characters are decimal digits and the symbols ‘+’, ‘-’, ‘*’, ‘/’, ‘(’, and ‘)’.
  • The parentheses in s are guaranteed to be valid and balanced.

4. Solutions

Stack

n = str.size()
Time complexity: O(n)
Space complexity: O(1)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
public:
    int maxDepth(const string &str) {
        int max_depth = 0, depth = 0;
        for (char c : str) {
            if (c == '(') {
                ++depth;
                max_depth = max(max_depth, depth);
            } else if (c == ')') {
                --depth;
            }
        }

        return max_depth;
    }
};
comments powered by Disqus