Sponsored
Sponsored
This approach utilizes a single counter to track the current depth of nesting while iterating through the string. Whenever an open parenthesis '(' is encountered, the counter is incremented, and whenever a closing parenthesis ')' is encountered, the counter is decremented. The maximum value of the counter at any point during the iteration is recorded as the maximum nesting depth.
Time Complexity: O(n), where n is the length of the string. Space Complexity: O(1), as only a few variables are used.
1public class MaxDepth {
2 public static int maxDepth(String s) {
3 int current_depth = 0, max_depth = 0;
4 for (char c : s.toCharArray()) {
5 if (c == '(') {
6 current_depth++;
7 max_depth = Math.max(max_depth, current_depth);
8 } else if (c == ')') {
9 current_depth--;
10 }
11 }
12 return max_depth;
13 }
14
15 public static void main(String[] args) {
16 String s = "(1+(2*3)+((8)/4))+1";
17 System.out.println("Max Depth: " + maxDepth(s));
18 }
19}
The Java solution reads characters from the string and uses them to adjust the depth counters, similar to the previous language implementations. The depth is updated for '(' and reduced for ')'.
This approach uses a stack to simulate the depth of nested parentheses. Each time an open parenthesis '(' is encountered, it is pushed onto the stack, and for each closing parenthesis ')', an item is popped. The maximum size of the stack during this process reflects the maximum nesting depth.
Time Complexity: O(n). Space Complexity: O(n) due to stack usage.
1
In the Java implementation, a character stack records each opening parenthesis, with stack size indicating depth. The maximum stack size is tracked to return maximum depth.