DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

Decode String - I

Can be done with recursion but for now I will go with Stack..

var decodeString = function (s) {
  let stackItem = [];
  for (let i = 0; i < a.length; i++) {
    if (a[i] === "]") {
      let tempNum = "";
      let tempStr = "";
      while (stackItem[stackItem.length - 1] !== "[") {
        tempStr = stackItem.pop() + tempStr;
      }
      stackItem.pop();
      while (!isNaN(stackItem[stackItem.length - 1])) {
        tempNum = stackItem.pop() + tempNum;
      }
      let finalstr = "";
      for (let j = 0; j < tempNum; j++) {
        finalstr += tempStr;
      }
      stackItem.push(finalstr);
    } else {
      stackItem.push(a[i]);
    }
  }

  return stackItem.join("");
};

Enter fullscreen mode Exit fullscreen mode

Top comments (0)