Checking Matched Delimiters with a Stack

A delimiter stack records which opener needs to be closed next, so it checks order as well as counts.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace valid nesting
  2. Locate two invalid paths
  3. Stop when the most recent opener requires a different symbol
  4. Test both ends of incomplete input

Trace valid nesting

When reading ([]), push the parenthesis, then the bracket. The closing bracket removes the current top and the closing parenthesis removes the earlier opener. A stack's last-in order matches nested structure.

Locate two invalid paths

The sequence ([)] fails at the first mismatched closer despite equal counts of each symbol. A closer with an empty stack fails immediately, while a leftover opener fails at end of input. Use small boundary tests for each completion rule.[1]

Stop when the most recent opener requires a different symbol

Reading ([)] pushes opening parenthesis and then opening bracket. The next closing parenthesis conflicts with the bracket at the top. Equal counts of each delimiter cannot prove nesting order. A stack stores the kind and optionally the position of each unmatched opener. See stack order.

position 0: ( → [(]
position 1: [ → [(, []
position 2: ) → expected ]
result: mismatch at position 2

Test both ends of incomplete input

An unmatched closer may arrive while the stack is empty. An unmatched opener may remain when all input has been consumed. Quoted strings and comments require lexical handling if their delimiters should be ignored. Confirm those rules independently from nesting.

References

  1. Jeff Erickson, Algorithms ↩