[3차] 압축

발자·2023년 6월 7일
0

programmers

목록 보기
28/34

문제

def solution(msg):
    # 1. 길이가 1인 모든 단어를 포함하도록 사전을 초기화한다.
    ing = [s for s in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ']
    ing_dict = dict()
    for idx in range(len(ing)):
        ing_dict[ing[idx]] = idx + 1
    idx += 1
    
    answer = []
    while msg != '':
        # 2. 사전에서 현재 입력과 일치하는 가장 긴 문자열 w를 찾는다.
        if msg in ing_dict.keys():
            answer.append(ing_dict[msg])
            msg = ''
            break
        n = 0
        tmp = msg[n]
        while tmp in ing_dict.keys() and n < len(msg):
            n += 1
            tmp += msg[n]
        # 3. w에 해당하는 사전의 색인 번호를 출력하고, 입력에서 w를 제거한다.
        answer.append(ing_dict[tmp[:-1]])
        msg = msg[n:]
        # 4. 입력에서 처리되지 않은 다음 글자가 남아있다면(c), w+c에 해당하는 단어를 사전에 등록한다.
        idx += 1
        ing_dict[tmp] = idx
    
    return answer

0개의 댓글