개발/알고리즘

프로그래머스 문자열 압축 C++

daisy-day 2021. 2. 14. 18:00

문제

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

 

코딩테스트 연습 - 문자열 압축

데이터 처리 전문가가 되고 싶은 어피치는 문자열을 압축하는 방법에 대해 공부를 하고 있습니다. 최근에 대량의 데이터 처리를 위한 간단한 비손실 압축 방법에 대해 공부를 하고 있는데, 문자

programmers.co.kr

코드

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int solution(string s) {
    int answer = s.size();
    for (int i = 1; i <= s.size() / 2; i++) 
    {
        string str, temp;

        int cnt = 1;
        temp = s.substr(0, i);

        //앞에서 자른 문자열 다음부터 시작하는 문자열을 검사한다.
        for (int j = i; j < s.size(); j += i) 
        {
            //자른 문자열이 검사하는 문자열이랑 일치하는 경우
            if (temp == s.substr(j, i))
            {
                cnt++;
            }
            else 
            {
                if (cnt > 1)
                {
                    str += to_string(cnt);
                }

                str += temp;
                temp = s.substr(j, i);
                cnt = 1;
            }
        }

        if (cnt > 1)
        {
            str += to_string(cnt);
        }

        str += temp;
        answer = min(answer, (int)str.size());
    }
    return answer;
}