forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDecode String.java
More file actions
39 lines (34 loc) · 1.07 KB
/
Decode String.java
File metadata and controls
39 lines (34 loc) · 1.07 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
class Solution {
public static String decodeString(String s) {
Stack<Integer> count = new Stack<>();
Stack<String> str = new Stack<>();
int i = 0;
str.push("");
while(i < s.length()) {
if (s.charAt(i) >= '0' && s.charAt(i) <= '9') {
int start = i;
while (s.charAt(i+1) >= '0' && s.charAt(i+1) <= '9') {
i++;
}
count.push(Integer.parseInt(s.substring(start, i + 1)));
}
else if (s.charAt(i) == '[') {
str.push("");
}
else if (s.charAt(i) == ']') {
String st = str.pop();
StringBuilder sb = new StringBuilder();
int n = count.pop();
for (int j = 0; j < n; j++) {
sb.append(st);
}
str.push(str.pop() + sb.toString());
}
else {
str.push(str.pop() + s.charAt(i));
}
i++;
}
return str.pop();
}
}