Decode String
Given an encoded string, return its decoded string (e.g., 3[a]2[bc] -> aaabcbc).
- 1 <= s.length <= 30
- s consists of lowercase English letters, digits, and square brackets
- s is guaranteed to be a valid input
s = "3[a]2[bc]""aaabcbc"s = "3[a2[c]]""accaccacc"When you see a pattern like 3[a2[c]], you are looking at a Dependency Chain. You want to repeat something 3 times, but that something is not fully known yet—it is a plus whatever 2[c] turns into. You are stuck in a waiting game: you cannot finish the outer 3 expansion until you have completely finished the inner 2 expansion first.
This Last-In, First-Resolved priority is why a Stack is needed. It allows us to put our current task on a shelf and focus entirely on the newest sub-task that just appeared. Once the sub-task is done, we grab the old task back off the shelf and merge the result.
We move through the string one character at a time, keeping a Current Workspace (the string we are building) and a Current Multiplier (the number we just read).
- The '[' (Enter New Sub-Task): We have hit a nested pattern! We cannot finish our current work yet. We Push our Current Workspace and Current Multiplier onto the Stack for safekeeping. Then, we clear our workspace to start fresh on the inner pattern.
- Alphabet Letters: Just keep building the string in your Current Workspace.
- The ']' (Finish Sub-Task): We have finished an inner pattern! Now we must merge it back.
- Pop the saved multiplier and the saved Previous Workspace from the Stack.
- Multiply our finished inner string by the multiplier.
- Glue it onto the end of the Previous Workspace.
- Our Current Workspace is now this merged result.
stack = []
current_string = ""
current_multiplier = 0
FOR each character in string:
IF character is a Digit:
current_multiplier = (current_multiplier * 10) + digit
ELSE IF character is '[':
// PAUSE: Save context
stack.PUSH([current_string, current_multiplier])
current_string = ""
current_multiplier = 0
ELSE IF character is ']':
// RESUME: Pop and expand
[prev_string, num] = stack.POP()
current_string = prev_string + (current_string * num)
ELSE:
current_string += character
RETURN current_stringDual-Stack Checkpointing for Nested Structures
Decoding '3[a]2[bc]'. Prepare stacks for nested expansion.
Use stacks to "checkpoint" the current state (string and multiplier) before diving into a nested bracket.