-
Notifications
You must be signed in to change notification settings - Fork 0
/
394. 字符串解码.java
52 lines (44 loc) · 1.81 KB
/
394. 字符串解码.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
44
45
46
47
48
49
50
51
52
import java.util.Stack;
public class Main {
public static String decodeString(String s) {
Stack<Integer> countStack = new Stack<>();
Stack<StringBuilder> stringStack = new Stack<>();
StringBuilder currentString = new StringBuilder();
int k = 0;
for (char ch : s.toCharArray()) {
if (Character.isDigit(ch)) {
k = k * 10 + (ch - '0');
} else if (ch == '[') {
// Push the current count and current string onto their stacks
countStack.push(k);
stringStack.push(currentString);
// Reset for the next segment
currentString = new StringBuilder();
k = 0;
} else if (ch == ']') {
// Pop the count and previous string
int repeatTimes = countStack.pop();
StringBuilder decodedString = stringStack.pop();
// Append the current string repeatTimes times
for (int i = 0; i < repeatTimes; i++) {
decodedString.append(currentString);
}
// Update currentString to the decoded string
currentString = decodedString;
} else {
currentString.append(ch);
}
}
return currentString.toString();
}
public static void main(String[] args) {
String s1 = "3[a]2[bc]";
System.out.println(decodeString(s1)); // Output: "aaabcbc"
String s2 = "3[a2[c]]";
System.out.println(decodeString(s2)); // Output: "accaccacc"
String s3 = "2[abc]3[cd]ef";
System.out.println(decodeString(s3)); // Output: "abcabccdcdcdef"
String s4 = "abc3[cd]xyz";
System.out.println(decodeString(s4)); // Output: "abccdcdcdxyz"
}
}