-
Notifications
You must be signed in to change notification settings - Fork 0
/
Decode.java
42 lines (40 loc) · 1.03 KB
/
Decode.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
39
40
41
42
class Decode {
public String deCompress(String s) {
if (s == null || s.length() == 0) return s;
return deCompress(s.toCharArray(), new int[1]).toString();
}
private StringBuilder deCompress(char[] array, int[] index) {
StringBuilder sb = new StringBuilder();
int count = 0;
while (index[0] < array.length) {
if (Character.isDigit(array[index[0]])) {
while (array[index[0]] != '|') {
count = count * 10 + (array[index[0]] - '0');
index[0]++;
}
// skip '|'
index[0]++;
} else if (Character.isLetter(array[index[0]])) {
sb.append(array[index[0]++]);
} else if (array[index[0]] == '[') {
index[0]++;
sb.append(deCompress(array, index));
} else {
// find ']'
index[0]++;
StringBuilder res = new StringBuilder();
while (count > 0) {
count--;
res.append(sb);
}
return res;
}
}
return sb;
}
public static void main(String[] args) {
Decode solve = new Decode();
String input = "HG[3|B[2|CA]]F";
System.out.println(solve.deCompress(input));
}
}