[PRO] 문자열 압축

천호영·2022년 7월 29일
0

알고리즘

목록 보기
41/100
post-thumbnail

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

반복횟수가 2자리가 넘어가는 경우를 생각못하고 항상 1을 더해서 초반에 틀렸던 문제

from collections import defaultdict

def solution(s):
    ans = float('inf')
    
    # cut_len: 자르는 길이
    for cut_len in range(1,len(s)+1):
        now_cnt = 0
        
        list_of_str_cnt_list = []
        for i in range(0,len(s),cut_len):
            now_str = s[i:i+cut_len]
            
            if list_of_str_cnt_list and list_of_str_cnt_list[-1][0]==now_str:
                list_of_str_cnt_list[-1][1] += 1
            else:
                list_of_str_cnt_list.append([now_str,1])
        
        
        for str_cnt_list in list_of_str_cnt_list:
            now_cnt += len(str_cnt_list[0])
            if str_cnt_list[1] != 1:
                now_cnt += len(str(str_cnt_list[1]))  # 여기 항상 1 더해주는게 아니다
        
        ans = min(ans, now_cnt)
        
    return ans
  • len(s)//2까지만 해도 된다. 그 이후는 그냥 붙여야됨.
profile
성장!

0개의 댓글