상세 컨텐츠

본문 제목

[코테] 프로그래머스 Lv2. [3차] 압축

코테

by Graceful_IT 2024. 1. 1. 22:03

본문

LZW 압축은 다음 과정을 거친다.

 

https://school.programmers.co.kr/learn/courses/30/lessons/17684

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

A~Z을 포함하는 사전을 아스키코드로 바꾸는 ord()함수와, 아스키에 해당하는 글자를 만드는 chr() 함수를 통해서 만들었다.

 

처음에는 포인터 2개를 사용해서 사전에 새로 들어가야 할 문자열을 관리하고자 하였지만 w+c가 어디까지 길어질 지 모르는 상태로 경우의 수를 나누기에는 너무 많다는 것을 깨달았다.

    while two < len(msg):
        if two+1 < len(msg) and msg[one:two+2] not in indexs:
            answer.append(indexs.index(msg[one])+1)
            indexs.append(msg[one:two+2])
            one+=1
        elif one+1 < len(msg) and msg[one:two+2] in indexs:
            answer.append(indexs.index(msg[one:two+2])+1)
            indexs.append(msg[one:two+3])
            one+=3

 

다른 블로그를 참고하여 문제를 풀 수 있었는데 for i in range(1,len(msg)+1): 라는 for 반복문과 msg=msg[i-1:] 코드를 사용하여 msg의 길이를 줄여나가며 푸는 것이 해답이었다.

 

def solution(msg):
    answer = []
    indexs = []
    cnt = ord('A')
    
    for i in range(26):
        indexs.append(chr(cnt))
        cnt+=1
        
    while True:
        if msg in indexs:
            answer.append(indexs.index(msg)+1)
            break
            
        for i in range(1,len(msg)+1):
            if msg[0:i] not in indexs:
                answer.append(indexs.index(msg[0:i-1])+1)
                indexs.append(msg[0:i])
                msg=msg[i-1:]
                break
        
    
    return answer

관련글 더보기