Given a string s
representing a valid parentheses string, return the maximum nesting depth of the parentheses.
A valid parentheses string is defined as follows:
""
(an empty string) is a valid parentheses string.s
is a valid parentheses string if s
is formed by concatenation of two valid parentheses strings.s
is a valid parentheses string if s
is formed by wrapping a valid parentheses string with a pair of parentheses.The nesting depth of "((()))"
is 3, while the nesting depth of "()(())"
is 2.
'('
and ')'
.0
.def maxDepth(s: str) -> int:
max_depth = 0
current_depth = 0
for char in s:
if char == '(':
current_depth += 1
if current_depth > max_depth:
max_depth = current_depth
elif char == ')':
current_depth -= 1
return max_depth
# Example usage:
input_string = "((()))"
print(maxDepth(input_string)) # Output: 3
max_depth
and current_depth
to keep track of the maximum nesting depth observed and the current depth respectively.'('
, increment the current_depth
by 1.max_depth
if the current_depth
is greater than max_depth
.')'
, decrement the current_depth
by 1.max_depth
will be the maximum nesting depth.n
is the length of the input string. We iterate through the string once.max_depth
and current_depth
variables, regardless of the input size.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?