<Programmers> 문자열 압축 c++

Google 아니고 Joogle·2022년 2월 15일
0

Programmers

목록 보기
14/22
post-thumbnail

Programmers 문자열 압축

  1. 문자열을 자르는 단위의 길이를 1개부터 문자열의 총 길이만큼을 기준으로 잘라본다
  2. 처음에 길이가 i인 단위가 되는 문자열을 temp에 저장하고 (temp=s.substr(0,i)) 바로 뒤에 있는 문자열이 temp와 같으면 cnt를 증가시키고, 다르다면 string convert (새로 변환한 문자를 저장하는 string)에 저장한다.
  3. convert에 저장한 후 현재 위치(j)부터 i길이인 문자열을 다시 단위가 되는 문자열로 바꾸기 위해 temp에 저장 (temp=s.substr(j,i);)
  4. 단위가 되는 길이 i가 바뀔 때마다 convert의 길이를 비교하여 최소가 되는 길이를 반환한다.
#include <string>
#include <vector>

using namespace std;

int solution(string s) {
    int answer = s.size();

    for (int i=1; i<=s.size(); i++) {
        string convert, 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) convert+=to_string(cnt);
                convert+=temp;
                temp=s.substr(j,i);
                cnt=1;
            }
        }
        if (cnt>1) convert+=to_string(cnt);
        convert+=temp; 
        if (answer>convert.size()) answer=convert.size();
    }
    return answer;
}

profile
Backend 개발자 지망생

0개의 댓글