공부하고 기록하는, 경제학과 출신 개발자의 노트

프로그래밍/코딩테스트 문제풀이

[Python] 프로그래머스. 2018 카카오 recruit - 압축 (Level 2)

inspirit941 2020. 3. 3. 16:28
반응형

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

주어진 문제 요구대로 코딩하면 되는 문제.

 

현재 입력 + 다음 단어가 색인되어 있지 않을 경우

- "현재 입력"의 색인을 배열에 저장한다.

- "현재 입력 + 다음 단어" 조합을 새로 색인한다

- "현재 입력"에 다음 단어를 대입한다.

 

 

 

 

def solution(msg):
table = dict()
for idx, value in enumerate("ABCDEFGHIJKLMNOPQRSTUVWXYZ",1):
table[value] = idx
last_idx = idx
idx = 1
answer = []
letter = msg[0]
while idx < len(msg):
# 현재 입력 + 다음 글자 조합이 색인에 없는 경우
if letter + msg[idx] not in table:
# 현재 입력을 answer 배열에 저장
answer.append(table[letter])
# 새 단어의 색인값 저장
last_idx += 1
table[letter + msg[idx]] = last_idx
# 현재 입력 = '다음 단어'로 저장
letter = msg[idx]
# 다음 단어
idx += 1
continue
# 이미 색인되어 있는 단어의 경우, 다음 단어를 현재 입력에 추가
letter += msg[idx]
idx += 1
answer.append(table[letter])
return answer
반응형