-
Notifications
You must be signed in to change notification settings - Fork 7
/
StringDecoder.java
43 lines (37 loc) · 1.46 KB
/
StringDecoder.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
43
package stack;
import java.util.Stack;
public class StringDecoder {
public String decodeString(String s) {
Stack<Integer> numStack = new Stack<>();
Stack<StringBuilder> strStack = new Stack<>();
StringBuilder currentString = new StringBuilder();
int num = 0;
for (char c : s.toCharArray()) {
if (Character.isDigit(c)) {
num = num * 10 + c - '0';
} else if (c == '[') {
strStack.push(currentString);
currentString = new StringBuilder();
numStack.push(num);
num = 0;
} else if (c == ']') {
StringBuilder temp = currentString;
currentString = strStack.pop();
int count = numStack.pop();
for (int i = 0; i < count; i++) {
currentString.append(temp);
}
} else {
currentString.append(c);
}
}
return currentString.toString();
}
public static void main(String[] args) {
StringDecoder decoder = new StringDecoder();
assert decoder.decodeString("3[a]2[bc]").equals("aaabcbc") : "Test case 1 failed";
assert decoder.decodeString("3[a2[c]]").equals("accaccacc") : "Test case 2 failed";
assert decoder.decodeString("2[abc]3[cd]ef").equals("abcabccdcdcdef") : "Test case 3 failed";
System.out.println("All test cases passed!");
}
}