awelgorithms

Push an opening bracket

Updated

On an opener (, [, {, push it. The stack remembers the nearest unmatched opener. Closers will consult that top.

What to focus on

Do not push closers. After a push, the top is that opener. Nested openers stack: "(([" leaves ['(', '(', '['] with top '['.

Worked examples

one

s = "("
  1. push (

Result: stack ['(']

nested

s = "(["
  1. push (
  2. push [

Result: stack ['(', '['] · top '['

three types

s = "({["
  1. push (, {, [

Result: stack ['(', '{', '['] · top '['

Try it

Write pushOpeners(s). s is a string of opening brackets only. Walk left to right and push each opener. Do not push a closer. Print the stack. Top is the last opener. On "([" and "({[" the top must be '['.

s is a non-empty string of opening brackets (, [, { only.