-
Notifications
You must be signed in to change notification settings - Fork 0
/
26.DecodeString.java
46 lines (43 loc) · 2.04 KB
/
26.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
43
44
45
46
import java.util.Stack;
class Solution {
public String decodeString(String s) {
// Stack to keep track of the count of repetitions
Stack<Integer> countStack = new Stack<>();
// Stack to keep track of the previous strings before encountering a '[' character
Stack<StringBuilder> stringStack = new Stack<>();
// StringBuilder to build the current string being processed
StringBuilder currentString = new StringBuilder();
// Variable to keep track of the count of repetitions
int count = 0;
// Iterate through each character in the input string
for (char ch : s.toCharArray()) {
if (Character.isDigit(ch)) {
// If the character is a digit, update the count of repetitions
count = count * 10 + (ch - '0');
} else if (ch == '[') {
// If the character is '[', push the current count to countStack
// Push the currentString to stringStack
// Reset currentString and count for the inner string
countStack.push(count);
stringStack.push(currentString);
currentString = new StringBuilder();
count = 0;
} else if (ch == ']') {
// If the character is ']', pop the count and previous string from stacks
int repeatTimes = countStack.pop();
StringBuilder decodedString = stringStack.pop();
// Append the currentString to the previous string 'repeatTimes' times
for (int i = 0; i < repeatTimes; i++) {
decodedString.append(currentString);
}
// Update currentString to the decodedString
currentString = decodedString;
} else {
// If the character is a letter, append it to the currentString
currentString.append(ch);
}
}
// Return the final decoded string
return currentString.toString();
}
}