Decode String
Given an encoded string, return its decoded string.
The encoding rule is: k[encoded_string]encoded_stringkk
You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc.
Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k3a2[4]
The test cases are generated so that the length of the output will never exceed 105
Example 1
Output: "aaabcbc"
Example 2
Output: "accaccacc"
Example 3
Output: "abcabccdcdcdef"
Constraints:
1 <= s.length <= 30 consists of lowercase English letters, digits, and square bracketss .'[]' is guaranteed to be a valid input.s- All the integers in
are in the ranges .[1, 300]
Contents
Solution 1 - Using a Stack
In this approach, we are going to loop through every character of input string sStack']'[stack'['2[abc]abc]"abc"
Then, if the stack0-9[stack
import java.util.Stack;
public class DecodeString {
static String decodeString(String s) {
Stack<String> stack = new Stack<>();
for(char c: s.toCharArray()) {
if( c != ']') {
stack.push(String.valueOf(c));
} else {
String current ="";
while (!"[".equals(stack.peek())) {
current = stack.pop() + current;
}
stack.pop(); // pop the '['
// now we need to get the K number before that
String k = "";
while(!stack.isEmpty() && Character.isDigit(stack.peek().toCharArray()[0])) {
k = stack.pop() + k;
}
String decoded = current.repeat(Integer.parseInt(k));
stack.push(decoded);
}
}
return String.join("", stack);
}
public static void main(String[] args) {
System.out.println(decodeString("2[abc]3[cd]ef"));
}
}
Complexity Analysis:
Time complexity: Time complexity really depends on how big is the knk'sO (n * k)
Space complexity: O(n * k) for storing elements into stack.
Above implementations source code can be found at