Track nesting depth with a stack
Updated
Depth is the stack size while scanning. Each opener +1, each matching closer −1. Max size is max depth.
What to focus on
You can track depth as an integer if there is only one bracket type. Multiple types still need the stack for matching, and size is the depth.
Worked examples
max 2
s = "(())"- size 1,2,1,0
- max 2
Result: depth max 2
max 1
s = "()()"- 1,0,1,0
- max 1
Result: depth max 1
max 3
s = "((()))"- size 1,2,3,2,1,0
- max 3
Result: depth max 3
Try it
Write maxDepth(s). s is a well-formed string of one bracket type. Return the maximum size. Do not print. "(())" max 2. "()()" max 1. "((()))" max 3.
s is a well-formed non-empty string of one bracket type. Depth never goes negative.