-
Notifications
You must be signed in to change notification settings - Fork 383
Expand file tree
/
Copy pathDecode String.java
More file actions
32 lines (32 loc) · 925 Bytes
/
Decode String.java
File metadata and controls
32 lines (32 loc) · 925 Bytes
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
class Solution {
public String decodeString(String s) {
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (c == ']') {
StringBuilder sb = new StringBuilder();
while (!stack.isEmpty() && stack.peek() != '[') {
sb.append(stack.pop());
}
stack.pop();
String temp = sb.toString();
sb.setLength(0);
while (!stack.isEmpty() && Character.isDigit(stack.peek())) {
sb.append(stack.pop());
}
int count = Integer.parseInt(sb.reverse().toString());
while (count-- > 0) {
for (int i = temp.length() - 1; i >= 0; i--) {
stack.push(temp.charAt(i));
}
}
} else {
stack.push(c);
}
}
StringBuilder sb = new StringBuilder();
while (!stack.isEmpty()) {
sb.append(stack.pop());
}
return sb.reverse().toString();
}
}