awelgorithms

Pop on a matching closer

Updated

On a closer, the top must be the matching opener. Then pop. That closer is resolved. After a successful pop, the new top is the next unmatched opener, or empty.

What to focus on

')' matches '('. ']' matches '['. '}' matches '{'.

Worked examples

simple

s = "()", stack after '('
  1. see )
  2. top is (
  3. pop

Result: [] · balanced so far

nested

s = "([])", after "(["
  1. see ]
  2. top is [
  3. pop
  4. then ) matches remaining (

Result: []

adjacent

s = "()()"
  1. push pop, push pop

Result: []

Try it

Write matchClosers(s). s is a string of brackets. On each closer, pop if the top is the matching opener. Finish with an empty stack. Trace "()", "([])", and "()()". Each closer pops the matching top. Finish empty.

s is a well-formed string of (), [], {}. Every closer matches the current top.