-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecodestring
More file actions
50 lines (40 loc) · 1.25 KB
/
Copy pathdecodestring
File metadata and controls
50 lines (40 loc) · 1.25 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
class Solution {
public String decodeString(String s) {
Stack<Integer> numStack = new Stack<>();
Stack<String> stringStack = new Stack<>();
int k = 0;
for (char c : s.toCharArray()) {
if (Character.isDigit(c)) {
k = (k * 10) + (c - '0');
continue;
}
if (c == '[') {
numStack.push(k);
k = 0;
stringStack.push(String.valueOf(c));
continue;
}
if (c != ']') {
stringStack.push(String.valueOf(c));
continue;
}
StringBuilder temp = new StringBuilder();
while (!stringStack.peek().equals("["))
temp.insert(0, stringStack.pop());
// remove the "["
stringStack.pop();
// Get the new string
StringBuilder replacement = new StringBuilder();
int count = numStack.pop();
for (int i = 0; i < count; i++)
replacement.append(temp);
// Add it to the stack
stringStack.push(replacement.toString());
}
StringBuilder result = new StringBuilder();
while (!stringStack.empty()) {
result.insert(0, stringStack.pop());
}
return result.toString();
}
}