Categories
interview

Decode String (Js)

Given an encoded string 3[abc]2[bc] the decoded output should be of the form “abcabcabcbcbc”. Assume that all the brackets are well formed and that all strings are encoded correctly.

/**
 * @param {string} s
 * @return {string}
 */
const decodeString = (s) => {
  let stack = [];
  for (let i = 0; i < s.length; i++) {
    let ch = s.charAt(i);
    if (ch === ']') {
      let currStr = '';
      while (stack[stack.length - 1] !== '[') {
        currStr += stack.pop();
      }
      stack.pop();
      let k = 0,
        base = 1;
      while (stack.length > 0 && !isNaN(parseInt(stack[stack.length - 1]))) {
        k += parseInt(stack.pop()) * base;
        base *= 10;
      }
      while (k != 0) {
        for (let j = currStr.length - 1; j >= 0; j--) {
          stack.push(currStr.charAt(j));
        }
        k--;
      }
    } else {
      stack.push(ch);
    }
  }
  return stack.join('');
};

Demo