Decode String (LeetCode 394): Solution and Explanation
A string is encoded with the rule k[text], meaning text repeated k times, and these patterns can be nested. Given an encoded string, return the fully expanded version.
Watch it run step by step
Try your own input and write the code →Intuition
If there were no nesting, you could scan for a number, the bracketed text after it, and repeat it. Nesting is what makes this interesting: in 3[a2[c]], you cannot repeat the outer part until you know what the inner part expands to. Any time an inner structure must be finished before the outer one can be completed, that is a sign to reach for a stack or recursion.
Think about what you need to remember when you hit an opening bracket. You are about to start building a brand new piece of text, the part inside the brackets. But you must not forget two things: the text you had built so far at the outer level, and the number that came right before the bracket, which says how many times to repeat the inner text. So on [, push the pair (current_str, current_num) onto a stack and start fresh with an empty string and a zero count.
On ], the inner text is complete. Pop the saved pair, repeat the inner text the saved number of times, and append it to the saved outer text. That result becomes the new current string, and you continue at the outer level as if the whole bracketed group were ordinary letters. Digits simply accumulate into current_num (so multi-digit counts like 12 work), and letters append to current_str. When the scan ends, the stack is empty and current_str holds the answer.
Approach: Stack of saved string and count
- Initialize an empty
stack, an emptycurrent_str, andcurrent_num = 0. - For a digit, update
current_num = current_num * 10 + int(char)so multi-digit counts are read correctly. - For
[, push(current_str, current_num)onto the stack, then resetcurrent_strto empty andcurrent_numto 0. - For
], pop(prev_str, num)and setcurrent_str = prev_str + current_str * num. - For any letter, append it to
current_str. - After the loop, return
current_str.
Step-by-step example
s = "3[a2[c]]"
- Read 3, so
current_num = 3. Read[, push ("", 3), and reset to an empty string and 0. - Read a, so
current_str = "a". Read 2, socurrent_num = 2. - Read
[, push ("a", 2), and reset. Read c, socurrent_str = "c". - Read
], pop ("a", 2), and build "a" + "cc" = "acc". - Read the final
], pop ("", 3), and build "" + "acc" repeated 3 times = "accaccacc". - The input is finished, so the function returns "accaccacc".
Code: Python, Java, C++
1class Solution:
2 def decodeString(self, s: str) -> str:
3 stack = []
4 current_str = ""
5 current_num = 0
6
7 for char in s:
8 if char.isdigit():
9 current_num = current_num * 10 + int(char)
10 elif char == '[':
11 stack.append((current_str, current_num))
12 current_str = ""
13 current_num = 0
14 elif char == ']':
15 prev_str, num = stack.pop()
16 current_str = prev_str + current_str * num
17 else:
18 current_str += char
19
20 return current_str1class Solution {
2 public String decodeString(String s) {
3 Stack<Integer> numStack = new Stack<>();
4 Stack<StringBuilder> strStack = new Stack<>();
5 StringBuilder currentStr = new StringBuilder();
6 int currentNum = 0;
7
8 for (char c : s.toCharArray()) {
9 if (Character.isDigit(c)) {
10 currentNum = currentNum * 10 + (c - '0');
11 } else if (c == '[') {
12 numStack.push(currentNum);
13 strStack.push(currentStr);
14 currentNum = 0;
15 currentStr = new StringBuilder();
16 } else if (c == ']') {
17 int repeatTimes = numStack.pop();
18 StringBuilder temp = strStack.pop();
19 for (int i = 0; i < repeatTimes; i++) {
20 temp.append(currentStr);
21 }
22 currentStr = temp;
23 } else {
24 currentStr.append(c);
25 }
26 }
27 return currentStr.toString();
28 }
29}1class Solution {
2public:
3 string decodeString(string s) {
4 stack<int> numStack;
5 stack<string> strStack;
6 string currentStr = "";
7 int currentNum = 0;
8
9 for (char c : s) {
10 if (isdigit(c)) {
11 currentNum = currentNum * 10 + (c - '0');
12 } else if (c == '[') {
13 numStack.push(currentNum);
14 strStack.push(currentStr);
15 currentNum = 0;
16 currentStr = "";
17 } else if (c == ']') {
18 int repeatTimes = numStack.top(); numStack.pop();
19 string temp = strStack.top(); strStack.pop();
20 for (int i = 0; i < repeatTimes; i++) {
21 temp += currentStr;
22 }
23 currentStr = temp;
24 } else {
25 currentStr += c;
26 }
27 }
28 return currentStr;
29 }
30};Time and space complexity
O(d × L)
Here L is the length of the decoded output and d is the maximum nesting depth. Each closing bracket builds a new string no longer than the output, and a character of the output can be copied once per enclosing level, so the work is bounded by d × L and is close to linear for shallow nesting.
O(L)
The stack holds at most d saved prefixes, and together with the current string they never exceed the length of the final output.
Other approaches
Recursive descent (time O(d × L), space O(L))
Write a helper that reads from a shared index, building a string until it hits ] or the end. When it sees a number followed by [, it recurses to decode the inner part, then repeats it. It mirrors the grammar of the encoding directly and many people find it more readable, at the cost of recursion depth equal to the nesting depth.
Common mistakes
- Reading only single-digit counts. Inputs like
12[a]require accumulating digits withcurrent_num * 10 + digit. - Forgetting to reset
current_numto 0 after pushing at[, which makes the next count start from the previous one. - Pushing only the count and not the outer string. On
]you then lose the text that came before the bracket. - In Java, concatenating with
String +inside loops. UseStringBuilderfor the current string and the saved strings, or the solution slows down sharply on large outputs.
Frequently asked questions
Why use a stack for Decode String?
Brackets nest, and an inner group must be fully decoded before the outer group can be repeated. A stack remembers the outer context at each opening bracket and restores it in the right order at each closing bracket.
How do you handle multi-digit numbers like 100[a]?
Accumulate digits as you read them with current_num = current_num * 10 + digit, and only consume the number when you reach the opening bracket.
Stack or recursion for Decode String?
They are equivalent; the recursive version uses the call stack instead of an explicit one. The explicit stack avoids recursion limits, while recursion follows the nested structure more naturally.