Given a valid parentheses string s
, return the nesting depth of* s
. The nesting depth is the maximum number of nested parentheses.
Example 1:
Input: s = "(1+(2*3)+((8)/4))+1"
Output: 3
Explanation: Digit 8 is inside of 3 nested parentheses in the string.
Example 2:
Input: s = "(1)+((2))+(((3)))"
Output: 3
Explanation: Digit 3 is inside of 3 nested parentheses in the string.
Example 3:
Input: s = "()(())((()()))"
Output: 3
Constraints:
1 <= s.length <= 100
s
consists of digits 0-9
and characters '+'
, '-'
, '*'
, '/'
, '('
, and ')'
.s
is a VPS.## Nesting Depth of Valid Parentheses String
This problem asks us to find the maximum nesting depth of a valid parentheses string (VPS). A VPS is a string that consists of digits, '+', '-', '*', '/', '(', and ')', and has balanced parentheses. The nesting depth is the maximum number of nested parentheses at any point in the string.
### Brute Force Solution
A brute force solution would involve iterating through all possible substrings and checking if they are valid parentheses strings. If a substring is a valid parentheses string, we calculate its nesting depth. Finally, we find the maximum of all nesting depths.
However, this approach is inefficient because it involves generating all possible substrings and checking their validity, which can be time-consuming.
### Optimal Solution
We can solve this problem more efficiently by iterating through the string once and keeping track of the current nesting depth. We increment the depth when we encounter an opening parenthesis '(' and decrement it when we encounter a closing parenthesis ')'. The maximum depth encountered during the iteration is the nesting depth of the VPS.
```python
def max_depth(s: str) -> int:
"""Calculates the maximum nesting depth of a valid parentheses string.
Args:
s: The input string.
Returns:
The maximum nesting depth of the string.
"""
max_depth = 0
current_depth = 0
for char in s:
if char == '(': # Encountered an opening parenthesis
current_depth += 1
max_depth = max(max_depth, current_depth)
elif char == ')': # Encountered a closing parenthesis
current_depth -= 1
return max_depth
Example Usage:
s1 = "(1+(2*3)+((8)/4))+1"
print(f"The nesting depth of '{s1}' is: {max_depth(s1)}") # Output: 3
s2 = "(1)+((2))+(((3)))"
print(f"The nesting depth of '{s2}' is: {max_depth(s2)}") # Output: 3
s3 = "()(())((()()))"
print(f"The nesting depth of '{s3}' is: {max_depth(s3)}") # Output: 3
The run-time complexity of this solution is O(n), where n is the length of the string. We iterate through the string once to calculate the nesting depth.
The space complexity of this solution is O(1), as we only use a few constant space variables to store the current depth and maximum depth.
max_depth
(0) will be returned.if
and elif
conditions will never be met, so max_depth
will remain 0.current_depth
never goes below 0 and that it is 0 at the end of the iteration.