The prompt: Given an encoded string, return its corresponding decoded string. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is repeated exactly k times. Note: k is guaranteed to be a positive integer.
For s = "4[ab]", the output should be decodeString(s) = "abababab" For s = "2[b3[a]]", the output should be decodeString(s) = "baaabaaa"
My answer:
let decodeString = function(s) {
const replaced = s.replace((/(\d+)\[([a-z]*)\]/), (match, num, substr) => {
return substr.repeat(num);
})
return replaced.indexOf('[') > -1 ? decodeString(replaced) : replaced;
};
This solution works for smaller inputs like "3[a]2[bc]"
but I get stack overflow for more complex inputs like "3[a]2[b4[F]c]"
. Is there a way to do this iteratively to avoid using the call stack? Is it possible to solve this question by only using regex? Any help is much appreciated!