-
Notifications
You must be signed in to change notification settings - Fork 34
/
Solution.java
38 lines (38 loc) · 1.26 KB
/
Solution.java
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
public class Solution {
public String decodeString(String s) {
if (s.length() == 0) {
return "";
}
StringBuffer sb = new StringBuffer();
char[] cs = s.toCharArray();
int startNum = -1;
int startString = -1;
int bracketNums = 0;
for (int i = 0; i < cs.length; i++) {
if (cs[i] >= '0' && cs[i] <= '9') {
if (startNum == -1) {
startNum = i;
}
} else if (cs[i] == '[') {
if (startString == -1) {
startString = i;
}
bracketNums++;
} else if (cs[i] == ']') {
bracketNums--;
if (bracketNums == 0) {
int times = Integer.valueOf(s.substring(startNum, startString));
String son = decodeString(s.substring(startString + 1, i));
for (int j = 0; j < times; j++) {
sb.append(son);
}
startString = -1;
startNum = -1;
}
} else if (bracketNums == 0) {
sb.append(String.valueOf(cs[i]));
}
}
return sb.toString();
}
}