-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDecodeString.java
More file actions
44 lines (40 loc) · 1.19 KB
/
Copy pathDecodeString.java
File metadata and controls
44 lines (40 loc) · 1.19 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
42
43
44
class Solution {
public String decodeString(String s) {
if (s == null) return null;
Deque<Integer> nst = new ArrayDeque<>();
Deque<Character> st = new ArrayDeque<>();
int num = 0;
for (char x : s.toCharArray()) {
if (Character.isDigit(x)) {
num = num * 10 + x - '0';
} else if (x == '[') {
st.push(x);
nst.push(num);
num = 0;
} else if (x == ']') {
String tmp = "";
char t;
while ((t = st.pop()) != '[') {
tmp = t + tmp;
}
pushIntoStack(st, repeat(nst.pop(), tmp));
} else st.push(x);
}
String result = "";
while (!st.isEmpty()) result = st.pop() + result;
return result;
}
private String repeat(int t, String x) {
String s = "";
for (int i = 0; i < t; i++) {
s += x;
}
return s;
}
private void pushIntoStack(Deque<Character> st, String s) {
for (char x : s.toCharArray()) {
st.push(x);
}
}
}
// Solution 2: use recursive solution