Config Bracket Check

Easy · Stack & Monotonic Stack · about 12 min

A settings file is checked line by line before it is loaded. A line may contain three kinds of brackets, (), [] and {}, mixed with any other characters (letters, digits, spaces, commas, colons, quotes). The other characters are ignored.

Return True (true in JavaScript) if the brackets are balanced: every closing bracket matches the closest opening bracket of the same kind that is still open, and nothing is left open at the end. Otherwise return False. A line with no brackets at all is balanced.

Example: config_bracket_check("{name: [1, 2], tags: (a)}") → True

Example: config_bracket_check("([)]") → False (the ) arrives while [ is still open)

Constraints: the line has 0 to 10,000 characters.

Hints

  • Openers wait for their partner. Which opener must the next closer match?
  • Keep the openers on a stack. A closer must match the top, and the top is then removed.
  • Three ways to fail: a closer with an empty stack, a closer whose partner is not on top, and openers still on the stack at the end.

Learn the pattern first: the Stack & Monotonic Stack lesson.

More Stack & Monotonic Stack problems