KatInterview

Well-Formed Bracket Sequence Checker

Stacks & QueuesAuto-graded · 27 test cases
EasyAuto-gradedStacks & Queuesstackstringmatching

Last updated

Decide whether a string of three kinds of brackets is correctly nested, using a stack to enforce that the most recently opened bracket is closed first.

Well-Formed Bracket Sequence

You are given a string text made up only of the six characters (, ), [, ], { and }. Decide whether the brackets in it form a well-formed sequence.

A sequence is well-formed when all of the following hold:

  1. Each closing bracket ends an opening bracket of the same kind () with (, ] with [, } with {).
  2. Brackets are closed in the reverse order from which they were opened, so pairs may be nested but never cross each other.
  3. No closing bracket appears without a matching opening bracket before it, and no opening bracket is left unclosed at the end.

Return True if text is well-formed, otherwise return False.

Constraints

  • 1 <= len(text) <= 10^4
  • text contains only the characters ()[]{}
  • Return a boolean (True or False)

Examples

Example 1

Input: is_well_formed('()[]{}')

Output: True

Example 2

Input: is_well_formed('([)]')

Output: False

Example 3

Input: is_well_formed('{[]}')

Output: True

Hints

Hint 1

The bracket that was opened most recently must be the first one to be closed. Which data structure gives you that last-in, first-out behavior?

Hint 2

When you see a closing bracket, compare it with the most recent unmatched opening bracket. If none exists, or the kinds differ, the string is invalid. Be careful not to look at an empty structure.

Hint 3

Matching every closer is not enough. After scanning the whole string, make sure no opening brackets remain unmatched. Also note that counting each bracket type separately would wrongly accept a crossing case like `([)]`.