๐ 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์ ์ ์ฅํ๋ค.
'๐ Problem Solving > Programmers' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[ํ๋ก๊ทธ๋๋จธ์ค-Lv2] ๋ฉ์ฉกํ ์ฌ๊ฐํ / Python (0) | 2021.06.16 |
---|---|
[ํ๋ก๊ทธ๋๋จธ์ค-Lv2] ์ง์ง์ด ์ ๊ฑฐํ๊ธฐ / Python (0) | 2021.06.16 |
[ํ๋ก๊ทธ๋๋จธ์ค-Lv2] ๊ตฌ๋ช ๋ณดํธ / Python (0) | 2021.06.15 |
[ํ๋ก๊ทธ๋๋จธ์ค-Lv2] ์ฃผ์๊ฐ๊ฒฉ / Python (0) | 2021.06.15 |
[ํ๋ก๊ทธ๋๋จธ์ค-Lv2] ํฐ ์ ๋ง๋ค๊ธฐ / Python (0) | 2021.06.14 |