You are 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: 3Explanation: Digit 8 is inside of 3 nested parentheses in the string.
Example 2:
Input: s = "(1)+((2))+(((3)))"
Output: 3Explanation: Digit 3 is inside of 3 nested parentheses in the string.
Example 3:
Input: s = "()(())((()()))"
Output: 3Constraints:
1 <= s.length <= 100s consists of digits 0-9 and characters '+', '-', '*', '/', '(', and ')'.s is a VPS.class Solution:
def maxDepth(self, s: str) -> int:
res = 0
def dfs(i):
nonlocal res
if i == len(s):
return 0
cur = dfs(i + 1)
if s[i] == '(':
cur += 1
elif s[i] == ')':
cur -= 1
res = max(res, abs(cur))
return cur
dfs(0)
return resclass Solution:
def maxDepth(self, s: str) -> int:
res, stack = 0, []
for c in s:
if c == "(":
stack.append(c)
res = max(res, len(stack))
elif c == ")":
stack.pop()
return resclass Solution:
def maxDepth(self, s: str) -> int:
res = 0
cur = 0
for c in s:
if c == "(":
cur += 1
elif c == ")":
cur -= 1
res = max(res, cur)
return res