프로그래머스 - 문자열 압축 - Level 2

Byungwoong An·2021년 7월 1일
0

문제

풀이전략

  1. 문자열은 제일 앞부터 정해진 길이만큼 잘라야한다. 따라서 맨 앞부터 자를 수 없다면 문자열은 그냥 자를 수 없다.
  2. 길이만큼 자르면서 substr함수를 사용하는데, 이 함수를 잘 사용할 수 있도록 노력해야한다.

코드

#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 convert, temp;
        
        int cnt = 1;
        // 비교해야할 부분에 대한 체크, 또한 문제에서 제시했듯이 첫번쨰 index부터 비교해야함
        temp = s.substr(0,i);
        
        // 비교할 부분 다음부터의 확인
        // j는 비교하는 크기만큼 사이즈를 증가시킴
        for(int j=i; j<s.size(); j+=i){
            // 비교부분과 같다면 cnt++함
            if(temp == s.substr(j,i)) cnt++;
            else{
                // 더이상 비교부분과 같은 값이 없을떄
                if(cnt>1) convert += to_string(cnt);
                convert += temp;
                // 이후 temp는 그다음 부분으로 넘어간다
                temp = s.substr(j, i);
                cnt = 1;
            }
        }
        
        if(cnt >1) convert += to_string(cnt);
        convert += temp;
        printf("%s\n",convert.c_str());
        if(convert.size() < answer) answer = convert.size();
        
        
    }
    return answer;
}

소감

내가 해결하지 못하고 다른분의 코드를 가져왔다... substr을 아직 잘 사용하지 못하는거 같다. 다른분이 substr을 너무 멋있게 사용하셨다. 나도 이렇게 사용하는 법을 배워야겠다.

profile
No Pain No Gain

0개의 댓글