Maximum Nesting Depth of the Parentheses

The task requires us to find the maximum depth of parentheses in a given string. We can solve this problem using a stack-like approach without actually using a stack. We can use a counter to mimic the stack’s behavior.

Here is the Python code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
    def maxDepth(self, s: str) -> int:
        # Initialize a counter for the current depth and a variable for the maximum depth.
        curr_depth = max_depth = 0

        # Iterate over each character in the string.
        for char in s:
            # If the character is an opening bracket, increment the current depth.
            if char == '(':
                curr_depth += 1
                # If the current depth is greater than the maximum depth, update the maximum depth.
                if curr_depth > max_depth:
                    max_depth = curr_depth
            # If the character is a closing bracket, decrement the current depth.
            elif char == ')':
                curr_depth -= 1

        # Return the maximum depth.
        return max_depth

In this code, we initialize curr_depth and max_depth to zero. Then we iterate over each character in the string. If the character is an opening parenthesis, we increment curr_depth and update max_depth if curr_depth is greater. If the character is a closing parenthesis, we decrement curr_depth. In the end, max_depth contains the maximum depth of parentheses in the string.