1614. Maximum Nesting Depth of the Parentheses #1988
-
Topics: A string is a valid parentheses string (denoted VPS) if it meets one of the following:
We can similarly define the nesting depth
For example,
Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine the maximum nesting depth of parentheses in a given valid parentheses string (VPS). The nesting depth is defined as the maximum number of nested parentheses at any point in the string. Approach
Let's implement this solution in PHP: 1614. Maximum Nesting Depth of the Parentheses <?php
/**
* @param String $s
* @return Integer
*/
function maxDepth($s) {
$maxDepth = 0;
$currentDepth = 0;
$length = strlen($s);
for ($i = 0; $i < $length; $i++) {
if ($s[$i] == '(') {
$currentDepth++;
if ($currentDepth > $maxDepth) {
$maxDepth = $currentDepth;
}
} elseif ($s[$i] == ')') {
$currentDepth--;
}
}
return $maxDepth;
}
// Test cases
echo maxDepth("(1+(2*3)+((8)/4))+1") . "\n"; // Output: 3
echo maxDepth("(1)+((2))+(((3)))") . "\n"; // Output: 3
?> Explanation:
This approach efficiently tracks the nesting depth in real-time as we traverse the string, ensuring optimal performance with minimal space usage. The solution leverages the properties of a valid parentheses string to simplify the depth calculation. |
Beta Was this translation helpful? Give feedback.
We need to determine the maximum nesting depth of parentheses in a given valid parentheses string (VPS). The nesting depth is defined as the maximum number of nested parentheses at any point in the string.
Approach