Decode a nested repeat string
Updated
For strings like "3[ab]2[c]", a stack holds the string built so far and the repeat count waiting for a ']'. Digits accumulate a count, '[' pushes a checkpoint, letters append to the current fragment, ']' pops and expands.
What to focus on
Innermost ] resolves first (LIFO). After expand, the piece is appended to the previous fragment (the new top).
Worked examples
one group
s = "3[ab]"- count 3
- frag ab
- ] → ababab
Result: "ababab"
nested
s = "2[a3[b]]"- inner bbb
- outer a + bbb twice
Result: "abbbabbb"
plain
s = "ab"- no brackets
- append
Result: "ab"
Try it
Write decode(s). s is a well-formed decode string. Return the expanded string. The ] that closes the inner group runs first. s = \"3[ab]\" → \"ababab\". s = \"2[a3[b]]\" → \"abbbabbb\". s = \"ab\" → \"ab\".
s is a well-formed decode string: matching brackets, counts are positive integers, letters are lowercase. No leftover '['.