-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
35 lines (33 loc) · 1.01 KB
/
Copy pathSolution.java
File metadata and controls
35 lines (33 loc) · 1.01 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
import java.util.Stack;
class Solution {
//Time Complexity: O(n)
//Space Complexity: O(n)
public String decodeString(String s) {
if (s == null || s.length() == 0) {
return "";
}
Stack<Integer> countStack = new Stack<>();
Stack<StringBuilder> resStack = new Stack<>();
StringBuilder res = new StringBuilder();
int k = 0;
for (char ch : s.toCharArray()) {
if (Character.isDigit(ch)) {
k = k * 10 + ch - '0';
} else if (ch == '[') {
countStack.push(k);
resStack.push(res);
res = new StringBuilder();
k = 0;
} else if (ch == ']') {
StringBuilder temp = res;
res = resStack.pop();
for (k = countStack.pop(); k > 0; k --) {
res.append(temp);
}
} else {
res.append(ch);
}
}
return res.toString();
}
}