본문 바로가기

Coding Test/Programmers

[프로그래머스/파이썬] 문자열 압축

728x90

 

 

나의 풀이

ef solution(s):
    length = len(s)
    answer = length

    for n in range(1, length // 2 + 1):
        idx = n
        pattern = s[0:n]
        count = 1
        result = ''
        while True:
            if idx < length:
                if s[idx:idx + n] == pattern:
                    count += 1
                else:
                    if count != 1:
                        result += str(count) + pattern
                    else:
                        result += pattern
                    count = 1
                pattern = s[idx:idx + n]
                idx += n
            elif count > 1:
                result += str(count) + pattern
                break
            else:
                result += s[idx - n:]
                break
        answer = min(answer, len(result))

    return answer

 - 무식한 풀이라 개선할 점이 많다

 

 

보다 깔끔한 풀이

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, int(len(text)/2) + 1)) + [len(text)])

a = [
    "aabbaccc",
    "ababcdcdababcdcd",
    "abcabcdede",
    "abcabcabcabcdededededede",
    "xababcdcdababcdcd",

    'aaaaaa',
]

for x in a:
    print(solution(x))
반응형