Stop at the matching closer
Updated
Sometimes you start at an opener and need the index of its matching closer. Push/pop with indices until that opener is popped. The closer that pops it is the match.
What to focus on
Scan from the opener (or from the left, ignoring stuff before). When size returns to the depth just before that opener, you found its closer. Do not take the first closer in the string. That may belong to an inner pair.
Worked examples
outer
s = "(a[b]c)", opener at 0- inner [ ] pop first
- ) at the end pops the (
Result: match at last )
inner
s = "(a[b]c)", opener '['- next ] is its match
Result: match at ]
adjacent trap
s = "()()", first (- first ) matches it
- not the second )
Result: index 1
Try it
Write matchingCloser(s, i). s is a well-formed string. i is the index of an opener. Letters between brackets are payload, not brackets. Return the index of the closer that pops that opener. Do not take an inner pair's closer. For "(a[b]c)", '(' matches the last ')'. '[' matches ']'. For "()()", the first '(' matches index 1, not the second ')'.
s is well-formed: every opener in the drill has a matching closer. Letters between brackets are payload, not brackets.