Decode String
Difficulty: Medium · Pattern: Stack & Monotonic Stack · LeetCode #394
Decode a string encoded as k[encoded], meaning encoded repeated k times. Encodings can nest. The input is always valid, and digits only appear as repeat counts.
Examples
text
"3[a]2[bc]" → "aaabcbc"
"3[a2[c]]" → "accaccacc"
"2[abc]3[cd]ef" → "abcabccdcdcdef"Hints
- Nesting suggests a stack: when you see
[, save what you've built so far and the count. - On
], pop and combine: previous + current × count. - Counts can have multiple digits.
Approach
Scan characters, keeping cur (the string being built) and num (the pending count). Digit: num = num·10 + d. [: push (cur, num), reset both. ]: pop (prev, k) and set cur = prev + cur·k. Letter: append to cur. O(output length).
Complexity
Time: O(length of the decoded output). Space: O(output + nesting depth).
Python solution
def decodeString(s):
stack, cur, num = [], "", 0
for ch in s:
if ch.isdigit():
num = num * 10 + int(ch)
elif ch == "[":
stack.append((cur, num)); cur, num = "", 0
elif ch == "]":
prev, k = stack.pop()
cur = prev + cur * k
else:
cur += ch
return curJavaScript solution
function decodeString(s) {
const stack = []; let cur = '', num = 0;
for (const ch of s) {
if (ch >= '0' && ch <= '9') num = num * 10 + Number(ch);
else if (ch === '[') { stack.push([cur, num]); cur = ''; num = 0; }
else if (ch === ']') { const [prev, k] = stack.pop(); cur = prev + cur.repeat(k); }
else cur += ch;
}
return cur;
}