Given an encoded string, return its decoded string.
The encoding rule is: k[encoded_string]
, where the encoded_string
inside the square brackets is being repeated exactly k
times. Note that k
is guaranteed to be a positive integer.
You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.
import java.util.Stack;
public class DecodeString {
public String decodeString(String s) {
Stack<Integer> countStack = new Stack<>();
Stack<String> 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 == '[') {
countStack.push(k);
stringStack.push(currentString.toString());
currentString = new StringBuilder();
k = 0; // reset k for new number
} else if (ch == ']') {
StringBuilder decodedString = new StringBuilder(stringStack.pop());
int repeatTimes = countStack.pop();
for (int i = 0; i < repeatTimes; i++) {
decodedString.append(currentString);
}
currentString = decodedString;
} else {
currentString.append(ch);
}
}
return currentString.toString();
}
public static void main(String[] args) {
DecodeString solution = new DecodeString();
System.out.println(solution.decodeString("3[a]2[bc]")); // "aaabcbc"
System.out.println(solution.decodeString("3[a2[c]]")); // "accaccacc"
System.out.println(solution.decodeString("2[abc]3[cd]ef")); // "abcabccdcdcdef"
}
}
n
is the length of the input string s
. This is due to the fact that each character in the string is processed exactly once.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?