Decode String
Master this topic with zero to advance depth.
Decode String
Decode an encoded string where k[encoded_string] means encoded_string is repeated k times.
Visual Representation
s = "3[a]2[bc]"
1. '3': k = 3
2. '[': Push 3, Push "". Stack: [(3, "")]
3. 'a': curr = "a"
4. ']': Pop 3. res = "" + "a"*3 = "aaa"
5. '2': k = 2
6. '[': Push 2, Push "aaa". Stack: [(2, "aaa")]
7. "bc": curr = "bc"
8. ']': Pop 2. res = "aaa" + "bc"*2 = "aaabcbc"Examples
Level I: Brute Force (Innermost Bracket First)
Intuition
Find the innermost [] bracket pair using regex or string searching, expand it (repeat the inner string by the preceding number), replace it in the original string, and repeat until no brackets remain. This naturally handles nested brackets by working from inside out.
Level III: Optimal (Two Stacks)
Intuition
Use two stacks: one to store the multipliers (countStack) and one to store the strings built so far (resStack). When an opening bracket [ is met, push the current count and current string. When a closing bracket ] is met, pop the multiplier and the previous string, then append the repeated current string to the previous one.
Detailed Dry Run
| Char | countStack | resStack | currStr |
|---|---|---|---|
| '3' | [] | [] | "" (k=3) |
| '[' | [3] | [""] | "" |
| 'a' | [3] | [""] | "a" |
| ']' | [] | [] | "aaa" |
⚠️ Common Pitfalls & Tips
Multi-digit numbers (like 100[a]) must be handled. Nested brackets are naturally handled by the stack.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.