Optimal: two stacks (counts and partial strings)
Time O(output length) Space O(output length)Build the current string in a StringBuilder and read numbers digit by digit. On '[', push the count and the current builder, then start fresh. On ']', pop the count and the previous builder, and append the current string that many times to it.
s = "3[a2[c]]"counts(stack)
saved strings(stack)
current(vars)
Step 1/4Read 3, then '[': save count 3 and the empty string; start fresh.
import java.util.ArrayDeque;
import java.util.Deque;
class Solution {
public String decodeString(String s) {
Deque<Integer> counts = new ArrayDeque<>();
Deque<StringBuilder> saved = new ArrayDeque<>();
StringBuilder cur = new StringBuilder();
int k = 0;
for (char c : s.toCharArray()) {
if (Character.isDigit(c)) {
k = k * 10 + (c - '0');
} else if (c == '[') {
counts.push(k);
saved.push(cur);
cur = new StringBuilder();
k = 0;
} else if (c == ']') {
StringBuilder prev = saved.pop();
prev.append(cur.toString().repeat(counts.pop()));
cur = prev;
} else {
cur.append(c);
}
}
return cur.toString();
}
}Verdict: Each character of the output is written a bounded number of times.