-
-
Notifications
You must be signed in to change notification settings - Fork 610
/
DecodeString.java
42 lines (34 loc) · 1.2 KB
/
DecodeString.java
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
package problems.medium;
import java.util.Stack;
/**
* Created by sherxon on 1/30/17.
*/
public class DecodeString {
static String decodeString(String s) {
StringBuilder sb = new StringBuilder();
Stack<Character> stack = new Stack<>();
char[] a = s.toCharArray();
for (int i = 0; i < a.length; i++) {
if (a[i] == ']') {
String inString = "";
while (!stack.isEmpty() && stack.peek() != '[')
inString += stack.pop();
if (stack.peek() == '[') stack.pop();
StringBuilder num = new StringBuilder();
while (!stack.isEmpty() && Character.isDigit(stack.peek()))
num.append(stack.pop());
int lim = Integer.parseInt(num.reverse().toString());
for (int j = 0; j < lim; j++) {
for (int k = inString.length() - 1; k >= 0; k--) {
stack.add(inString.charAt(k));
}
}
} else
stack.push(a[i]);
}
while (!stack.isEmpty()) {
sb.append(stack.pop());
}
return sb.reverse().toString();
}
}