-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_394_decode_string.java
More file actions
55 lines (44 loc) · 1.49 KB
/
Copy path_394_decode_string.java
File metadata and controls
55 lines (44 loc) · 1.49 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
45
46
47
48
49
50
51
52
53
54
55
import java.util.Stack;
public class _394_decode_string {
public static String decodeString(String s) {
int n = s.length();
Stack<Character> stack = new Stack<>();
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
if (c == ']') {
String str = "";
// process
// loop until meet '['
while (stack.peek() != '[') {
str = stack.pop() + str;
}
// remove '['
stack.pop();
// get amount
String amount = "";
while (stack.isEmpty() == false && Character.isDigit(stack.peek())) {
amount = stack.pop() + amount;
}
// int amountNumber = Integer.parseInt(amount);
// multiple str amountNumber times
// str = str.repeat(amountNumber); // un- co
// add result "str" back to stack
for (int j = 0; j < str.length(); j++) {
stack.push(str.charAt(j));
}
} else {
stack.push(c);
}
}
String result = "";
while (stack.isEmpty() == false) {
result = stack.pop() + result;
}
return result;
}
public static void main(String[] args) {
String s = "2[ab2[cd]]";
String result = decodeString(s);
System.out.println(result);
}
}