Leetcode / 1614. Maximum Nesting Depth of the Parentheses
Pick a programming language:
Here is the source code for the solution to this problem.
// import java.util.Stack;
class Solution {
// Without stack
// time O(n)
// space O(1)
public int maxDepth(String s) {
int counter = 0;
int maximum = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
counter++;
if (counter > maximum) {
maximum = counter;
}
}
else if (s.charAt(i) == ')') {
counter--;
}
}
return maximum;
}
// Using stack
// time O(n)
// space O(n)
// public int maxDepth(String s) {
// Stack<Character> stack = new Stack<Character>();
// int maximum = 0;
// for (int i = 0; i < s.length(); i++) {
// if (s.charAt(i) == '(') {
// stack.push(s.charAt(i));
// if (stack.size() > maximum) {
// maximum = stack.size();
// }
// }
// else if (s.charAt(i) == ')') {
// stack.pop();
// }
// }
// return maximum;
// }
}
Did you like the lesson? 😆👍
Consider a donation to support our work: