awelgorithms

Push counts and fragments

Updated

On '[', push the current fragment and the current count, then reset both (fragment "", count 0) for the inner group. Digits before '[' built that count. Nested '[' pushes another pair.

What to focus on

Two stacks (counts, frags) or one stack of pairs. They must pop together. Forgetting to reset the fragment on '[' concatenates inner letters onto the outer too early.

Worked examples

open

s = "3[ab", at '['
  1. push frag "" and count 3
  2. reset

Result: inner building ab

nested open

s = "2[a3[", at second '['
  1. push frag "a" and count 3
  2. reset inner

Result: inner empty, outer a saved

no bracket

s = "ab"
  1. never push count

Result: only the fragment

Try it

Write pushCheckpoint(s). s is a well-formed decode prefix up to the '[' you stop at. At each '[', print the count and fragment you push, and what you reset to (fragment "", count 0). s = \"3[ab\", at '[' → inner building ab. s = \"2[a3[\", at second '[' → inner empty, outer a saved. s = \"ab\" → only the fragment.

s is a well-formed decode prefix up to the '[' you stop at. Counts are positive integers.