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 '('- see )
- top is (
- pop
Result: [] · balanced so far
nested
s = "([])", after "(["- see ]
- top is [
- pop
- then ) matches remaining (
Result: []
adjacent
s = "()()"- 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.