Algorithm/프로그래머스

[프로그래머스] 압축 (python)

hammii 2021. 10. 3. 15:59
728x90
반응형
 

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

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

programmers.co.kr

 

👩🏻‍💻 코드

from string import ascii_uppercase


def solution(msg):
    answer = []
    alpha_list = list(ascii_uppercase)
    alpha_dict = {}

    for i in range(26):
        alpha_dict[alpha_list[i]] = i + 1

    start = 0
    end = 1
    idx = 27

    w = ''
    c = ''
    msg += ' '
    while True:
        for i in range(end, len(msg) + 1):
            if msg[start:i] not in alpha_dict:
                w = msg[start:i - 1]
                c = msg[i - 1]
                end = i - 1
                break

        answer.append(alpha_dict[w])
        alpha_dict[w + c] = idx
        idx += 1

        start = end
        end = start + 1

        if c == ' ':
            break

    return answer

 

📝 정리

  1. alpha_dict에 {'문자열': index} 형태로 알파벳들을 저장한다
  2. start와 end를 이용해 w와 c를 찾는다
  3. answer에는 alpha_dict에서 w의 index 값을 저장한다
  4. alpha_dict에 {w+c: idx}를 추가한다
  5. 2~4를 반복한다

 

 

 

728x90
반응형