2020 KAKAO BLIND RECRUITMENT - 문자열 압축 (Level 2)

 

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


Code

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
32
33
34
35
36
37
38
def solution(s):
    if len(s) == 1:
        return 1

    rsts = []
    for size in range(1, len(s)//2+1):
        slices = []
        for i in range(0, len(s)-size+1, size):
            slice = s[i:i+size]
            slices.append(slice)
        else:
            remainder = s[i+size:]

        rst = ""
        for i, slice in enumerate(slices):
            if i == 0:
                ss = slice
                n = 1
                continue
            if ss == slice:
                n += 1
                if i == len(slices) - 1:
                    rst += f"{n}{ss}"
            else:
                if n > 1:
                    rst += f"{n}{ss}"
                else:
                    rst += f"{ss}"
                ss = slice
                n = 1
                if i == len(slices) - 1:
                    rst += f"{ss}"

        rst += remainder
        # print(size, rst)
        rsts.append(len(rst))

    return min(rsts)

Complexity

$O(n^3)$
$n = |s|$