Problem Description
Explanation
To find the maximum nesting depth of parentheses in a given valid parentheses string, we can use a simple algorithm. We iterate through the string character by character and maintain a count of open parentheses. The maximum depth encountered during this iteration will be our answer.
Algorithm:
- Initialize variables
maxDepth
andcurrentDepth
to 0. - Iterate through each character in the input string.
- If the character is an opening parenthesis '(', increment
currentDepth
by 1. - Update
maxDepth
to be the maximum ofmaxDepth
andcurrentDepth
. - If the character is a closing parenthesis ')', decrement
currentDepth
by 1. - Return
maxDepth
as the result.
Time Complexity: O(n) where n is the length of the input string. Space Complexity: O(1) as we are using constant extra space.
Solutions
class Solution {
public int maxDepth(String s) {
int maxDepth = 0;
int currentDepth = 0;
for (char c : s.toCharArray()) {
if (c == '(') {
currentDepth++;
maxDepth = Math.max(maxDepth, currentDepth);
} else if (c == ')') {
currentDepth--;
}
}
return maxDepth;
}
}
Loading editor...