PROGRAMMERS
[프로그래머스/파이썬] [3차] 압축
kode-daks
2025. 1. 20. 15:43
내 풀이
from collections import deque
def solution(msg):
answer = []
m_queue = deque(msg)
next_index = 27
# 대문자만 포함한 사전 생성
LZW_dict = {}
for i in range(1, 27):
LZW_dict[chr(i+64)] = i
while m_queue:
w = m_queue.popleft()
if m_queue:
c = m_queue.popleft()
else: # 마지막일 경우 아무 문자도 추가 X
c = ''
while w+c in LZW_dict: # 없을 때까지 w 업데이트
w = w+c
if m_queue:
c = m_queue.popleft()
else:
c = ''
break
answer.append(LZW_dict[w]) # 사전에 존재하는 제일 긴 단어
LZW_dict[w+c] = next_index # 그 다음 길이의 단어 사전에 추가
next_index += 1
if c: # 마지막이 아니라면 새로운 w로 시작할 수 있게 큐에 다시 추가
m_queue.appendleft(c)
return answer
메모
졸리다..