Decode String
Medium
Topics
Given an encoded string s following the rule k[encoded] meaning the bracketed part repeats k times, return the decoded string.
Example 1
[ and popped at ]. Counts can be multi-digit, so they are accumulated rather than read one character at a time. Result: aaabcbc.Input: s = "3[a]2[bc]" Output: "aaabcbc"
Example 2
Input: s = "3[a2[c]]" Output: "accaccacc"
Constraints
- 1 <= s.length <= 30
- Digits are only for repeat counts.
Editorial — intuition, approach, complexity and pitfalls
Intuition
The encoding nests — 3[a2[c]] has a repeat inside a repeat — so the decoder has to suspend what it is building, handle the inner group, then resume. Suspend-and-resume is a stack.
Two things must be saved when a [ opens: the string built so far at this level, and the repeat count that applies to the group about to start. On the matching ], pop both, multiply the inner result by the count, and append it to the saved prefix.
The multi-digit parse matters: 12[a] means twelve repeats, so digits accumulate with num = num * 10 + digit rather than being read one at a time.
Approach
- Keep
current(the string at this level) andnum(the pending count). - Digit: extend
num. [: push(current, num), reset both.]: pop(prefix, k), setcurrent = prefix + current * k.- Letter: append to
current.
Dry Run
s = "3[a2[c]]"
3 num=3
[ push ("", 3) current="" num=0
a current="a"
2 num=2
[ push ("a", 2) current="" num=0
c current="c"
] pop ("a",2) -> current = "a" + "c"*2 = "acc"
] pop ("",3) -> current = "" + "acc"*3 = "accaccacc"
answer "accaccacc"The inner ] is the instructive step: current holds only "c", because the [ reset it, and the saved "a" is what the outer level had accumulated.
Complexity
- Time — O(length of the output): every character of the result is produced once. Expressing it in terms of the input is misleading —
10[10[10[a]]]is 14 characters of input and a thousand of output, so the output length is the honest measure. - Space — O(length of the output): the stack holds one saved prefix per nesting level, and those prefixes together are bounded by the result.
Common Pitfalls
- Reading digits one at a time, so
12[a]becomes one repeat then two. - Pushing the count but not the prefix. The text before
[belongs to the outer level and must survive the inner group. - Appending before multiplying on
]. The count applies to the inner group only, not to the prefix. - Resetting
numbut notcurrenton[, which duplicates the prefix into the inner group. - Trying to decode with a regex or a single pass without a stack. Nesting is unbounded, so neither works.
Full Solution — all languages
class Solution:
def decodeString(self, s):
stack = []
cur = ""
num = 0
for c in s:
if c.isdigit():
num = num * 10 + int(c)
elif c == "[":
stack.append((cur, num))
cur = ""
num = 0
elif c == "]":
prev, k = stack.pop()
cur = prev + cur * k
else:
cur += c
return curimport java.util.*;
class Solution {
public String decodeString(String s) {
Deque<String> strs = new ArrayDeque<>();
Deque<Integer> nums = new ArrayDeque<>();
StringBuilder cur = new StringBuilder();
int num = 0;
for (char c : s.toCharArray()) {
if (Character.isDigit(c)) num = num * 10 + (c - '0');
else if (c == '[') {
strs.push(cur.toString());
nums.push(num);
cur = new StringBuilder();
num = 0;
} else if (c == ']') {
int k = nums.pop();
StringBuilder tmp = new StringBuilder(strs.pop());
for (int i = 0; i < k; i++) tmp.append(cur);
cur = tmp;
} else cur.append(c);
}
return cur.toString();
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: string decodeString(string s) {
vector<string> strs;
vector<int> nums;
string cur;
int num = 0;
for (char c : s) {
if (isdigit(c)) num = num * 10 + (c - '0');
else if (c == '[') {
strs.push_back(cur);
nums.push_back(num);
cur = "";
num = 0;
} else if (c == ']') {
int k = nums.back();
nums.pop_back();
string prev = strs.back();
strs.pop_back();
string rep;
for (int i = 0; i < k; i++) rep += cur;
cur = prev + rep;
} else cur += c;
}
return cur;
}
};/**
* @param {string} s
* @return {string}
*/ var decodeString = function(s) {
const stack = [];
let cur = "", num = 0;
for (const c of s) {
if (c >= '0' && c <= '9') num = num * 10 + (+c);
else if (c === '[') {
stack.push([cur, num]);
cur = "";
num = 0;
} else if (c === ']') {
const [prev, k] = stack.pop();
cur = prev + cur.repeat(k);
} else cur += c;
}
return cur;
};