awelgorithms

Parse nested pairs

Updated

Nested pairs are openers whose matching closer comes after an inner complete pair. The inner pair push-pops while the outer opener stays buried, then the outer closer pops it.

What to focus on

"( [ ] )" : outer stays on the stack during the inner pair. Adjacent pairs "()()" bury nothing. Each pair completes before the next opener.

Worked examples

nested

s = "([])"
  1. ( stays while [ ] resolve
  2. then ) pops (

Result: nested

inner then outer done

s = "(())"
  1. inner () at depth 2
  2. then outer

Result: nested same type

not nested

s = "()()"
  1. stack empty between pairs

Result: adjacent

Try it

Write classifyNested(s). s is a well-formed string of (), []. Print the stack after each character. Nested means an opener is still on the stack during an inner pair. "([])" nested. "(())" nested same type. "()()" adjacent (stack empty between pairs).

s is a well-formed non-empty string of (), [].