awelgorithms

Handle multiple bracket types

Updated

Each closer matches exactly one opener type. The stack stores which kind is open. Counts of each type are not enough: "([)]" has equal counts and is still invalid because the nearest opener is wrong.

What to focus on

Map )→(, ]→[, }→{. Peek, compare, pop. A single stack handles all types because nesting is still LIFO across types.

Worked examples

mixed good

s = "([]{})"
  1. each closer matches its top

Result: valid

crossed

s = "([)]"
  1. ] vs ( or ) vs [ — nearest fails

Result: invalid

same type nested

s = "[[]]"
  1. two [ then two ]

Result: valid

Try it

Write isValid(s). s is a string of (), [], {}. Each closer must match the current top type. Equal counts do not save crossed types. "([]{})" is valid. "([)]" is invalid. "[[]]" is valid.

s is a non-empty string of (), [], {}. Crossed types are in scope. That is this skill.