study
문자열 압축[프로그래머스]
Date: 2026-06-01 07:27
Update: 2026-06-01 07:32
문자열 압축[프로그래머스]
접근법:
- 최소 1개 단위에서 최대 문자열의 절반 단위 까지 압축한다.
- 문자열의 절반인 이유는 절반 초과라면 오히려 문자열의 길이가 늘어나기 때문
- 현재 단위 만큼 맨 앞에서 문자열을 잘라 기준 문자열로 삼는다.
- 단위 만큼 이동하며 나오는 문자열과 기준 문자열을 비교한다.
- 일치할 경우 count 를 증가시킨다.
- 일치 하지 않을 때까지 반복한다.
- count의 갯수에 따라서 숫자를 넣을지 말지 결정한다.
- 기준문자열을 결과물에 저장한다.
- 단위 * count 만큼 이동한다.
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
string compress(int n, const string& s)
{
string result;
for(int i = 0; i < s.size();)
{
int count = 1;
string sub = s.substr(i, n);
while(i + n * count < s.size())
{
string sub2 = s.substr(i + n * count, n);
if(sub == sub2) count++;
else break;
}
if(count >= 2)
{
result += to_string(count);
}
result += sub;
i += n * count;
}
return result;
}
int solution(string s) {
int answer = s.size();
int n = s.size();
for(int i = 1; i <= n / 2; ++i)
{
int size = compress(i, s).size();
answer = min(size, answer);
}
return answer;
}
.gif)