Algorithm Day72 - Decode String
🧩 Problem Description
Given an encoded string, return its decoded string.
The encoding rule is: k[encoded_string]
, where the encoded_string
inside the square brackets is being repeated exactly k
times.
Note that k
is guaranteed to be a positive integer.
💬 Examples
Example 1
1 | Input: s = "3[a]2[bc]" |
Example 2
1 | Input: s = "3[a2[c]]" |
Example 3
1 | Input: s = "2[abc]3[cd]ef" |
Example 4
1 | Input: s = "abc3[cd]xyz" |
💡 Intuition
We can use two stacks to decode the string:
- One stack for numbers (repeat counts).
- One stack for strings (previous built results).
- Traverse the input string:
- If digit → build number.
- If
[
→ push current string and number to stacks. - If
]
→ pop count and previous string, repeat current substring and append. - Otherwise → append characters to current string.
🔢 Java Code (Stack Approach)
1 | import java.util.*; |
⏱ Complexity Analysis
- Time: O(n) — each character processed once.
- Space: O(n) — stacks for numbers and strings.
✍️ Summary
- Use two stacks: one for counts, one for partial strings.
- Build substrings iteratively while handling nested brackets.
Related problems
lc-224
— Basic Calculatorlc-227
— Basic Calculator IIlc-20
— Valid Parentheses