-
Notifications
You must be signed in to change notification settings - Fork 13
/
Solution394.java
50 lines (45 loc) · 1.34 KB
/
Solution394.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
43
44
45
46
47
48
49
50
package algorithm.leetcode;
import java.util.LinkedList;
/**
* @author: mayuan
* @desc: 字符串解码
* @date: 2019/03/15
*/
public class Solution394 {
public String decodeString(String s) {
if (null == s || 0 >= s.length()) {
return "";
}
String ans = "";
LinkedList<String> resStack = new LinkedList<>();
LinkedList<Integer> numberStack = new LinkedList<>();
int idx = 0;
while (idx < s.length()) {
char c = s.charAt(idx);
if (Character.isDigit(c)) {
int num = 0;
while (Character.isDigit(s.charAt(idx))) {
num = num * 10 + (s.charAt(idx) - '0');
++idx;
}
numberStack.push(num);
} else if ('[' == c) {
resStack.push(ans);
ans = "";
++idx;
} else if (']' == c) {
StringBuilder stringBuilder = new StringBuilder(resStack.pop());
int repeat = numberStack.pop();
while (0 < repeat--) {
stringBuilder.append(ans);
}
ans = stringBuilder.toString();
++idx;
} else {
ans += c;
++idx;
}
}
return ans;
}
}