Poison

394. Decode String

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public String decodeString(String s) {
Stack<StringBuilder> cacheStack = new Stack<>();
cacheStack.push(new StringBuilder());
Stack<Integer> numStack = new Stack<>();

int num = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c >= '0' && c <= '9') {
num = num * 10 + (c - '0');
} else if (c == '[') {
numStack.push(num);
num = 0;
cacheStack.push(new StringBuilder());
} else if (c == ']') {
StringBuilder part = cacheStack.pop();
int count = numStack.pop();
for (int j = 0; j < count; j++) {
cacheStack.peek().append(part);
}
} else {
// c is alpha
cacheStack.peek().append(c);
}
}

return cacheStack.pop().toString();
}
}
Reference

394. Decode String