1614. Maximum Nesting Depth of the Parentheses

When it comes to processing strings containing parentheses, such as mathematical expressions or structured data, determining the maximum depth of these parentheses can be a useful task. In this blog, we’ll delve into a Java solution that accomplishes this task efficiently.

``````import java.util.Stack;

class Solution {
public int maxDepth(String s) {
char c[] = s.toCharArray();
int max = 0;
Stack<Character> stack = new Stack<Character>();
for(int i = 0; i < c.length; i++) {
if (c[i] == '(') {
stack.push('(');
} else if (c[i] == ')') {
stack.pop();
}
if (max < stack.size()) {
max = stack.size();
}
}
return max;
}
}
``````

his `Solution` class contains a method `maxDepth(String s)` that takes a string `s` as input and calculates the maximum depth of parentheses in that string.

Approach:

1. Initialization: We initialize a variable `max` to keep track of the maximum depth encountered so far. We also use a stack to keep track of opening parentheses.
2. Processing: We iterate through each character in the string. If the character is an opening parenthesis `(`, we push it onto the stack. If it’s a closing parenthesis `)`, we pop an element from the stack.
3. Depth Calculation: After each operation, we check if the current stack size is greater than `max`. If it is, we update `max` to the current stack size.
4. Completion: Once we’ve processed all characters in the string, `max` will hold the maximum depth of parentheses encountered.

https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/description/?envType=daily-question&envId=2024-04-04