Decode String
Expand a string such as 3[a2[c]], where a number before brackets repeats the text inside them.
Given an encoded string sk[text]textkk
Example 1
Output: "aaabcbc"
Example 2
Output: "accaccacc"
Explanation: the inner "2[c]" becomes "cc", so the outer part is "3[acc]".
The Idea
The encoding works like brackets in arithmetic. In 3 × (1 + 2 × (4 + 5)) you cannot finish the outer bracket until the inner one is done. Example 1 has no bracket inside another, so each part can be finished on its own: 3[a]aaa2[bc]bcbcaaabcbc
Example 2 is where it gets interesting. Read 3[a2[c]]3[aa2[
We need two things: the count 3, and the text a
A pile where you can only add or take the top item has exactly this order: the last item put on is the first taken off. It is called a stack. Putting an item on top is a push, and taking the top item off is a pop. Look at the picture below. Each stack entry is a pair: a count, and the text built before its bracket opened. cur
In the column labelled "after 3[a", the first [(3, "")cura[(2, "a")curc
Now the closing brackets arrive. In "after the first ]", the top pair (2, "a")acacc(3, "")accaccaccacc
So each []
Solution Approach
Turning the stack idea into code means settling three things: how to read a count, what to save at []
Expanding one bracket at a time
Why not just find an innermost bracket, such as 2[c]cc
Reading a count
How many characters long is a count? It can have several digits, as in 10[a]kk = k * 10 + digit10[
Saving the outer state at [
What goes on the stack? The pair from the picture: the count kcurcurkcountsouter
Finishing a part at ]
What happens when a bracket closes? curcurcurcur
Optional: a recursive version
A method that calls itself can do the same work. On []s
Java Solution
The method decodeString
- First, create the two stacks:
for the repeat counts andcounts for the text built before eachouter . Both are[ objects, Java's usual choice for a stack. StartArrayDeque as an emptycur and the countStringBuilder at 0.k - Read the string one character
at a time with a loop. A digit extends the count:c .k = k * 10 + (c - '0') - At
, push[ ontok andcounts ontocur . Then giveouter a new empty builder and setcur back to 0.k - At
, keep the finished inner text as] . Pop the outer text intoinner , and appendcur to it.inner.repeat(counts.pop()) - Any other character is a letter, so append it to
. After the loop, returncur as a string.cur
The main
import java.util.ArrayDeque;
import java.util.Deque;
public class DecodeString {
public static String decodeString(String s) {
Deque<Integer> counts = new ArrayDeque<>();
Deque<StringBuilder> outer = new ArrayDeque<>(); // text built before each '['
StringBuilder cur = new StringBuilder();
int k = 0;
for (char c : s.toCharArray()) {
if (Character.isDigit(c)) {
k = k * 10 + (c - '0'); // counts can have several digits
} else if (c == '[') {
counts.push(k); // remember the count and the text so far
outer.push(cur);
cur = new StringBuilder(); // start the inner text
k = 0;
} else if (c == ']') {
String inner = cur.toString();
cur = outer.pop(); // back to the text before '['
cur.append(inner.repeat(counts.pop()));
} else {
cur.append(c);
}
}
return cur.toString();
}
public static void main(String[] args) {
System.out.println(decodeString("3[a]2[bc]"));
System.out.println(decodeString("3[a2[c]]"));
System.out.println(decodeString("2[abc]3[cd]ef"));
System.out.println(decodeString("2[a2[b]c]"));
System.out.println(decodeString("10[a]"));
System.out.println(decodeString("abc"));
}
}
Running it prints:
aaabcbc
accaccacc
abcabccdcdcdef
abbcabbc
aaaaaaaaaa
abc
aaabcbcaccaccacc2[a2[b]c]2[b]bbacabbcabbcabbcabc
Look at the fifth line: ten a10[a]k = c - '0'
Complexity
Let n be the length of s
- Time: O(n + d × L). The loop reads each of the n characters once. Each
copies its expanded text, so a letter of the answer that sits inside d brackets is copied once at every level on its way out.] - Space: O(L + d). The builders together hold no more than the characters of the answer, and each stack has one entry per open bracket, so at most d entries.