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.
1#include <stdio.h>
2#include <string.h>
3
4int maxDepth(char* s) {
5 int current_depth = 0, max_depth = 0;
6 for (int i = 0; s[i] != '\0'; i++) {
7 if (s[i] == '(') {
8 current_depth++;
9 if (current_depth > max_depth) {
10 max_depth = current_depth;
11 }
12 } else if (s[i] == ')') {
13 current_depth--;
14 }
15 }
16 return max_depth;
17}
18
19int main() {
20 char* s = "(1+(2*3)+((8)/4))+1";
21 printf("Max Depth: %d\n", maxDepth(s));
22 return 0;
23}
The code iterates through each character of the string. For each '(', the depth counter is increased and checked against the current maximum depth. For each ')', the depth counter is decreased. The maximum recorded depth is returned as the result.
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
This JavaScript function uses an array as a stack to manage parentheses, pushing and popping as it processes. The maximum array length at any point gives the maximum depth.