Senior
Condition Difficulty: MEDIUM Given an encoded string in the following format: k[encoded_text] Here, k is the number of repetitions of the encoded_text string. The string is guaranteed to have a correct format: no extra spaces, brackets are always correct, etc. Decode the string Example: Input: "3[a]2[bc]" Output: "aaabcbc" Input: "3[a2[c]]" Output: "accaccacc" Input: "2[abc]3[cd]ef" Output: "abcabccdcdcdef"
sobes.tech AI
Answer from AI
To decode a string in the format k[encoded_text], it is convenient to use a stack. The idea is to iterate through the characters of the string, accumulate numbers and strings, and when encountering ], extract the last repeated block and the number of repetitions from the stack, then form the decoded part.
Example solution in Java:
public String decodeString(String s) {
Stack<Integer> counts = new Stack<>();
Stack<StringBuilder> resultStack = new Stack<>();
StringBuilder current = new StringBuilder();
int k = 0;
for (char ch : s.toCharArray()) {
if (Character.isDigit(ch)) {
k = k * 10 + (ch - '0');
} else if (ch == '[') {
counts.push(k);
resultStack.push(current);
current = new StringBuilder();
k = 0;
} else if (ch == ']') {
StringBuilder decoded = resultStack.pop();
int count = counts.pop();
for (int i = 0; i < count; i++) {
decoded.append(current);
}
current = decoded;
} else {
current.append(ch);
}
}
return current.toString();
}
This code correctly handles nested structures and repetitions, as in the examples from the problem statement.