-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDecodeString.java
More file actions
39 lines (30 loc) · 994 Bytes
/
DecodeString.java
File metadata and controls
39 lines (30 loc) · 994 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
33
34
35
36
37
38
39
package Stacks;
import java.util.Stack;
public class DecodeString {
public static String decodeString(String s) {
Stack<Integer> numbers = new Stack<>();
Stack<StringBuilder> string = new Stack<>();
int n = s.length(), num = 0;
StringBuilder str = new StringBuilder();
for (char ch : s.toCharArray()) {
if (ch >= '0' && ch <= '9') {
num = (num * 10) + ch - '0';
} else if (ch == '[') {
string.push(str);
str = new StringBuilder();
numbers.push(num);
num = 0;
} else if (ch == ']') {
StringBuilder temp = str;
str = string.pop();
int count = numbers.pop();
while (count-- > 0) str.append(temp);
} else {
str.append(ch);
}
}
return str.toString();
}
public static void main(String[] args) {
}
}