[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค-Lv2] ๋ฌธ์ž์—ด ์••์ถ• / Python

๐Ÿ“š Problem Solving/Programmers

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ๋ฌธ์ž์—ด ์••์ถ•

๋ฐ์ดํ„ฐ ์ฒ˜๋ฆฌ ์ „๋ฌธ๊ฐ€๊ฐ€ ๋˜๊ณ  ์‹ถ์€ "์–ดํ”ผ์น˜"๋Š” ๋ฌธ์ž์—ด์„ ์••์ถ•ํ•˜๋Š” ๋ฐฉ๋ฒ•์— ๋Œ€ํ•ด ๊ณต๋ถ€๋ฅผ ํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ์ตœ๊ทผ์— ๋Œ€๋Ÿ‰์˜ ๋ฐ์ดํ„ฐ ์ฒ˜๋ฆฌ๋ฅผ ์œ„ํ•œ ๊ฐ„๋‹จํ•œ ๋น„์†์‹ค ์••์ถ• ๋ฐฉ๋ฒ•์— ๋Œ€ํ•ด ๊ณต๋ถ€๋ฅผ ํ•˜๊ณ  ์žˆ๋Š”๋ฐ, ๋ฌธ

programmers.co.kr

import sys

input = sys.stdin.readline

s = input().rstrip()


def solution(s):
    answer = len(s)
    for step in range(1, len(s) // 2 + 1):
        compressed = ""
        prev = s[0:step]
        count = 1
        for i in range(step, len(s), step):
            if prev == s[i : i + step]:
                count += 1
            else:
                compressed += str(count) + prev if count >= 2 else prev
                prev = s[i : i + step]
                count = 1
        compressed += str(count) + prev if count >= 2 else prev
        answer = min(answer, len(compressed))
    return answer


print(solution(s))

 

ํ•ด์„ค

์ตœ๋Œ€ ์••์ถ•ํ•  ๊ธธ์ด๋Š” ์›๋ž˜ ๋ฌธ์ž์—ด ๊ธธ์ด์˜ ์ ˆ๋ฐ˜์ด๋‹ค. ๊ทธ ๊ธธ์ด๋Š” step์ด๋‹ค.

 

1. step๋ณ„๋กœ ๋‹จ์–ด๋“ค์„ ๋น„๊ตํ•œ๋‹ค. ํ˜„์žฌ ๋‹จ์–ด์™€ ๋‹ค์Œ ๋‹จ์–ด๊ฐ€ ๊ฐ™๋‹ค๋ฉด count๋ฅผ ์ฆ๊ฐ€์‹œํ‚จ๋‹ค.

2. ํ˜„์žฌ ๋‹จ์–ด์™€ ๋‹ค์Œ ๋‹จ์–ด๊ฐ€ ๋‹ค๋ฅด๋‹ค๋ฉด compressed์— count์™€ ๋‹จ์–ด๋ฅผ ์ €์žฅํ•œ๋‹ค. count๊ฐ€ 0์ด๋ผ๋ฉด ๋‹จ์–ด๋งŒ ์ €์žฅํ•œ๋‹ค. ์ถ”๊ฐ€์ ์œผ๋กœ, ์ด์ œ ๋น„๊ตํ•  ๋‹จ์–ด๋Š” ๋‹ค์Œ ๋‹จ์–ด(prev[i:i+step])๊ฐ€ ๋œ๋‹ค.

3. ํ•œ ๋ฒˆ์˜ step ๊ณผ์ •์ด ๋๋‚˜๋ฉด ๋‚˜๋จธ์ง€ ๋ฌธ์ž์—ด์„ compressed์— ์ €์žฅํ•˜๊ณ  ์—ฌํƒœ ๊ตฌํ•œ compreesed์˜ ๊ธธ์ด์™€ ํ˜„์žฌ ๊ตฌํ•œ compressed์˜ ๊ธธ์ด๋ฅผ ๋น„๊ตํ•˜์—ฌ ๋” ์ž‘์€ ๊ธธ์ด์˜ compressed๋ฅผ answer์— ์ €์žฅํ•œ๋‹ค.