Expand when a closer arrives
Updated
On ']', poppedCount times concatenate the current inner fragment. Then append that expansion onto the popped outer fragment. That becomes the current fragment. Do not push the expansion. It is now the running string.
What to focus on
count 1 is a copy. Nested: this ] only expands one level.
Worked examples
simple
s = "3[ab]", at ']'- inner ab * 3 = ababab
- outer was empty
Result: "ababab"
nested inner
s = "2[a3[b]]", inner ']'- b * 3 = bbb
- append to outer a → abbb
Result: current "abbb", count 2 still waiting
outer ]
s = "2[a3[b]]", outer ']'- abbb * 2
Result: "abbbabbb"
Try it
Write expandCloser(s). s is a well-formed decode string. At each ], expand inner * count and append to the popped fragment. Print the current fragment after each ]. s = \"3[ab]\", at ']' → \"ababab\". s = \"2[a3[b]]\", inner ']' → current \"abbb\", count 2 still waiting. s = \"2[a3[b]]\", outer ']' → \"abbbabbb\".
s is well-formed: every ] has a matching '[' and a positive count on the stack.