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.Before attempting this problem, you should be comfortable with:
We can process the string from right to left using recursion. Each open parenthesis increases our depth count, and each close parenthesis decreases it. By tracking the maximum absolute value of this count at any point, we find the deepest nesting level. Processing from right to left means we encounter closing parentheses first, which decrement the counter, and opening parentheses later, which increment it.
res to track the maximum depth.0. At each step, first recurse to the next index to get the running count.(, increment the count. If it's ), decrement the count.res with the maximum of res and the absolute value of the count.A stack naturally models nested structures. Each time we see an opening parenthesis, we push it onto the stack, increasing the current depth. Each closing parenthesis pops from the stack, decreasing the depth. The maximum stack size during traversal equals the maximum nesting depth.
res = 0.(, push it onto the stack and update res with the maximum of res and the current stack size.), pop from the stack.res after processing all characters.We don't actually need to store the parentheses in a stack. Since we only care about the depth (stack size), we can replace the stack with a simple counter. This reduces space complexity to O(1) while maintaining the same logic.
res = 0 to track the maximum depth and cur = 0 to track the current depth.(, increment cur. If it's ), decrement cur.res with the maximum of res and cur.res.A frequent mistake is incrementing or decrementing the depth counter for every character in the string. The string may contain digits, operators, and other characters that should be ignored. Only parentheses ( and ) affect the nesting depth.
When using a counter approach, the maximum depth should be updated after incrementing for (, not after decrementing for ). Updating after processing ) will miss the peak depth that occurred when the matching ( was processed.