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:
- 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. - 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. - Depth Calculation: After each operation, we check if the current stack size is greater than
max
. If it is, we updatemax
to the current stack size. - Completion: Once we’ve processed all characters in the string,
max
will hold the maximum depth of parentheses encountered.