awelgorithms

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
  1. inner [ ] pop first
  2. ) at the end pops the (

Result: match at last )

inner

s = "(a[b]c)", opener '['
  1. next ] is its match

Result: match at ]

adjacent trap

s = "()()", first (
  1. first ) matches it
  2. 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.