Decode String – Solution & Complexity
Solution Walkthrough
Step 1: Recursive-descent parser
- Parse the string left to right, carrying the current index through recursive calls.
- Accumulate multi-digit repeat counts until you reach
[. - When a
[opens a nested group, recursively decode that group and return both the decoded substring and the index of its matching]. - Append the nested result repeated
ktimes, then continue scanning from the character after].
Step 2: Iterative explicit-stack parser
- Keep one stack for the partially built strings from outer scopes and another for the repeat counts attached to them.
- Read digits into a multi-digit
count, push(currentString, count)when you see[, and reset the current builder for the nested block. - When you see
], pop the previous string and repeat count, expand the current substring, and prepend it to the previous outer string. - This avoids recursion and cleanly handles arbitrary nesting in one left-to-right pass.