-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution394.java
More file actions
41 lines (36 loc) · 1.17 KB
/
Solution394.java
File metadata and controls
41 lines (36 loc) · 1.17 KB
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
31
32
33
34
35
36
37
38
39
40
41
import java.util.Stack;
public class Solution394 {
public String decodeString(String s) {
StringBuilder sb = new StringBuilder();
Stack<StringBuilder> sbStack = new Stack<StringBuilder>();
Stack<Integer> numStack = new Stack<Integer>();
int num = 0;
for (char c : s.toCharArray()) {
if (Character.isDigit(c)) {
num = num * 10 + c - '0';
} else if (c == '[') {
sbStack.push(sb);
numStack.push(num);
sb = new StringBuilder();
num = 0;
} else if (c == ']') {
num = numStack.pop();
StringBuilder temp = sb;
sb = sbStack.pop();
for (int i = 0; i < num; i++) {
sb.append(temp);
}
num = 0;
} else {
sb.append(c);
}
}
return sb.toString();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Solution394 slu = new Solution394();
String s = "3[a2[c]]";
System.out.println(slu.decodeString(s));
}
}