연습장/프로그래머스 문제풀이

[프로그래머스 Level 2] 압축 - JavaScript

Tesseractjh 2022. 6. 10. 23:46

🔗 문제 링크

https://programmers.co.kr/learn/courses/30/lessons/17684

 

코딩테스트 연습 - [3차] 압축

TOBEORNOTTOBEORTOBEORNOT [20, 15, 2, 5, 15, 18, 14, 15, 20, 27, 29, 31, 36, 30, 32, 34]

programmers.co.kr

✏️ 풀이

function solution(msg) {
    const answer = [];
    const dictionary = [...Array(26)]
        .reduce((acc, _, i) => {
            acc[String.fromCharCode(65 + i)] = i + 1;
            return acc;
        }, {});
    let dictLength = 26;
    
    let i = 0;
    while (i < msg.length) {
        const curIndex = i;
        let target = msg[i];
        let nextTarget = msg.slice(curIndex, ++i + 1);
        while (i - 1 < msg.length && dictionary[nextTarget]) {
            target = nextTarget;
            nextTarget = msg.slice(curIndex, ++i + 1);
        }
        const index = dictionary[target];
        if (i < msg.length) {
            dictionary[nextTarget] = ++dictLength;
        }
        answer.push(index);
    }
    return answer;
}

먼저 dictionary에 A부터 Z까지 사전에 등록한다.

 

그 다음, 단어를 순회하면서 현재 인덱스부터 시작해서 인덱스를 증가시키면서 사전에 등록된 가장 긴 단어를 찾는다.

만약 현재 단어 뒤에 글자가 더 있고, (현재 단어 + 바로 뒷 글자)를 사전에 등록한다. 사전에 단어를 등록할 때에는 사전의 길이를 따로 dictLength에 저장하고 있다가 증가시키면서 등록시키게 하였다. 마지막으로 현재 단어에 대한 인덱스를 answer에 추가시킨다.

 

단어를 모두 순회하고 난 후 answer를 출력하였다.