본문 바로가기

프로그래머스

프로그래머스 LV2 [3차] 압축

728x90
import string
def solution(msg):
    answer = [];

    alpha_dict = {char: index + 1 for index, char in enumerate(string.ascii_uppercase)}
    print(alpha_dict)
    index = 26;
    
    while msg :
        wc = ""
        for i in range(len(msg)) :
            wc = wc + msg[i];
            if wc not in alpha_dict :
                # 사전에 새로운 단어 추가
                index += 1;
                alpha_dict[wc] = index;
                
                # answer에 추가하기
                wc = wc[:-1]
                answer.append(alpha_dict[wc]);
                break;
        msg = msg[len(wc):]
        if not msg :
            answer.append(alpha_dict[wc])
    return answer

풀이 및 회고

먼저 알파벳 딕셔너리를 생성합니다. 반복문을 통해 msg 를 순회하면서 딕셔너리에 없는 문자열이 있으면 먼저 딕셔너리에 추가해줍니다. 그리고 이전 문자열을 answer에 추가해줍니다. 그 후 msg를 앞으로 이동시켜줍니다.

마지막 문자열이 사전에 있을때를 대비해 마지막 코드를 실행합니다.

728x90