Today
Total
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
관리 메뉴

기억은 짧고 기록은 길다

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

CodingTest/programmers

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

ukunV 2021. 9. 17. 17:13

Link

 

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

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

programmers.co.kr

 

Solution

def solution(s):
    lens = []

    if len(s) == 1:
        return 1

    compact = ''
    for i in range(1, len(s) // 2 + 1):
        count = 1
        t = s[:i]
        for j in range(i, len(s), i):
            if s[j:j + i] == t:
                count += 1
            else:
                if count == 1:
                    count = ''
                compact += str(count) + t
                t = s[j: j + i]
                count = 1

        if count == 1:
            count = ''
        compact += str(count) + t
        lens.append(len(compact))
        compact = ''

    return min(lens)
🔑 key point:
        for j in range(i, len(s), i):
            if s[j:j + i] == t:
                count += 1
            else:
                if count == 1:
                    count = ''
                compact += str(count) + t
                t = s[j: j + i]
                count = 1

 

Other Solution

def compress(text, tok_len):
    words = [text[i:i + tok_len] for i in range(0, len(text), tok_len)]
    res = []
    cur_word = words[0]
    cur_cnt = 1
    for a, b in zip(words, words[1:] + ['']):
        if a == b:
            cur_cnt += 1
        else:
            res.append([cur_word, cur_cnt])
            cur_word = b
            cur_cnt = 1
    return sum(len(word) + (len(str(cnt)) if cnt > 1 else 0) for word, cnt in res)

def solution(text):
    return min(compress(text, tok_len) for tok_len in list(range(1, len(text) // 2 + 1)) + [len(text)])
Comments