Algorithm/Programmers

[프로그래머스] 문자열 압축 - Python

Dev.sohee 2021. 8. 16. 16:19

https://programmers.co.kr/learn/courses/30/lessons/60057

 

코딩테스트 연습 - 문자열 압축

데이터 처리 전문가가 되고 싶은 "어피치"는 문자열을 압축하는 방법에 대해 공부를 하고 있습니다. 최근에 대량의 데이터 처리를 위한 간단한 비손실 압축 방법에 대해 공부를 하고 있는데, 문

programmers.co.kr

 

def solution(s):
    answer = 1001
    
    if len(s) == 1:
        return 1
    
    for size in range(1, len(s)//2 + 1):
        compression = ''    
        piece = s[:size]
        cnt = 1
        
        for i in range(size, len(s), size):
            if piece == s[i:i+size]:
                cnt += 1
            else:
                if cnt != 1:
                    compression += str(cnt) + piece
                else:
                    compression += piece
                    
                cnt = 1
                piece = s[i:i+size]
                
        if cnt != 1:
            compression += str(cnt) + piece
        else:
            compression += piece
            
        answer = min(answer, len(compression))
        
    return answer