[3차] 압축

function solution(msg) {
  const answer = [];
  const msgToArr = msg.split("");
  const dictionary = {};
  for (let i = "A".charCodeAt(); i <= "Z".charCodeAt(); i++) {
    const currentChar = String.fromCharCode(i);
    dictionary[currentChar] = i - 64;
  }
  let lastIdx = 26;
  let longgest = 1;
  function recur(unit) {
    if (msgToArr.length == 0) {
      return answer;
    }
    const test = msgToArr.slice(0, unit).join("");
    if (dictionary.hasOwnProperty(test)) {
      answer.push(dictionary[test]);
      msgToArr.splice(0, unit);
      const newWord = test + msgToArr[0];
      dictionary[newWord] = lastIdx + 1;
      lastIdx++;
      if (newWord.length > longgest) {
        longgest++;
      }
      return recur(longgest);
    }
    return recur(unit - 1);
  }
  return recur(longgest);
}

0개의 댓글