프로그래머스
1. 구현
def solution(s):
answer = len(s)
for step in range(1, len(s) // 2 + 1):
compressed = ""
prev = s[0:step]
count = 1
for j in range(step, len(s), step):
if prev == s[j:j + step]:
count += 1
else:
compressed += str(count) + prev if count >= 2 else prev
prev = s[j:j + step]
count = 1
compressed += str(count) + prev if count >= 2 else prev
answer = min(answer, len(compressed))
return answer
2. C++ 코드
#include <bits/stdc++.h>
using namespace std;
int solution(string s) {
int answer = s.size();
for (int step = 1; step < s.size() / 2 + 1; step++) {
string compressed = "";
string prev = s.substr(0, step);
int cnt = 1;
for (int j = step; j < s.size(); j += step) {
if (prev == s.substr(j, step)) cnt += 1;
else {
compressed += (cnt >= 2)? to_string(cnt) + prev : prev;
prev = s.substr(j, step);
cnt = 1;
}
}
compressed += (cnt >= 2)? to_string(cnt) + prev : prev;
answer = min(answer, (int)compressed.size());
}
return answer;