Recognizing One Kind of Balanced Parenthesis

For a single bracket kind, a count of currently open brackets can track whether a prefix can still be extended to a balanced string.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace two words
  2. Check multiple kinds separately
  3. Reject as soon as one prefix closes too much
  4. Check final balance after all prefixes pass

Trace two words

For (()), the counts after each symbol are one, two, one, zero. For )(, the first count is negative and the prefix has no matching opener. See loop counts.

Check multiple kinds separately

A single count cannot distinguish ([)] from correctly nested variants. A delimiter stack retains each opener's kind.[1]

Reject as soon as one prefix closes too much

For a language with one type of parenthesis, increment balance on open and decrement on close. Input ())( ends at balance zero but has negative balance at its third position. It is therefore invalid under the nesting rule. See matching several kinds with a stack.

Prefix balances of ()(): 1,0,1,0 → valid
Prefix balances of ())(: 1,0,-1,0 → reject at -1

Check final balance after all prefixes pass

Input (() has no negative prefix but finishes with one unclosed opening symbol. Both the prefix rule and the final zero are necessary. Several delimiter types need information about kinds as well as counts.

References

  1. Michael Sipser, Introduction to the Theory of Computation ↩