-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.java
More file actions
51 lines (48 loc) · 1.25 KB
/
Copy pathSolution.java
File metadata and controls
51 lines (48 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
51
import java.util.*;
public class Solution
{
public String decodeString(String s)
{
Stack<String> words = new Stack<>();
Stack<Integer> counts = new Stack<>();
words.push("");
int i = 0;
while (i < s.length())
{
char c = s.charAt(i);
if (Character.isDigit(c))
{
int end = i;
while (Character.isDigit(s.charAt(end)))
{
end++;
}
int count = Integer.parseInt(s.substring(i, end));
counts.push(count);
i = end - 1;
}
else if (c == '[')
{
words.push("");
}
else if (c == ']')
{
StringBuilder sb = new StringBuilder();
int count = counts.pop();
String str = words.pop();
while (count > 0)
{
sb.append(str);
count--;
}
words.push(words.pop() + sb.toString());
}
else
{
words.push(words.pop() + c);
}
i++;
}
return words.pop();
}
}