[アルゴリズム]プログラマ文字列圧縮


このブログは、非商業的な学業のためにのみ投稿されています.

1.問題分析

  • 比較文字の数が固定されているので、簡単に言えば、1個、2個、…(文字列の長さ/2)単語を順番にカットして比較すればいいです.
  • 2.回答プロセス(挿入)

  • 最初は文字列を最適に圧縮すべきだと考えられていたが、圧縮された標準文字列の数は固定されているため、容易になった.
  • 3.トラブルシューティング

  • 分析によって解決された.
  • 4.コード

    #include <string>
    #include <vector>
    #include <algorithm>
    
    using namespace std;
    
    int solution(string s) {
        int answer = s.length();
        int cut = 1;
        for(;cut <= s.length() >> 1; cut++)
        {
            string before(s, 0, cut);
            string result = "";
            int count = 1;
            for(int i = cut; i < s.length(); i += cut)
            {
                string now(s, i, min({cut, (int)s.length() - i}));
                if(before == now)
                    count++;
                else
                {
                    if(count > 1)
                        result.append(to_string(count));
                    result += before;
                    before = now;
                    count = 1;
                }
            }
            
            if(count > 1)
                result.append(to_string(count));
            result += before;
            answer = min(answer, (int)result.length());
        }
        return answer;
    }

    5.学習の達人のコード

  • ジェネレータを使用して文字列を切り取り、次のコードはsubstrを使用して切り取り、Back Junのような環境で速度比較を行いたいと思います.
  • #include <string>
    #include <vector>
    #include <iostream>
    
    using namespace std;
    
    vector<string> convert(string s, int n)
    {
        vector<string> v;
        for(int i = 0 ; i <s.length() ; i+=n)
        {
            v.push_back(s.substr(i,n));
        }
        return v;
    }
    
    int solution(string s) {
        int answer = 0;
        vector<string> tok;
        string before;
        int cnt = 1;
        int min = s.length();
        string str="";
        for(int j = 1 ; j <= s.length()/2 ; j++)
        {
            tok = convert(s,j);
            str = "";
            before = tok[0];
            cnt = 1;
            for(int i = 1 ; i < tok.size() ; i++)
            {
                if(tok[i] == before) cnt++;
                else
                {
                    if(cnt != 1) str += to_string(cnt);
                    str += before;
                    before = tok[i];
                    cnt = 1;
                }
            }
            if(cnt != 1)str += to_string(cnt);
            str += before;  
            min = min<str.length() ? min : str.length();
        }
        cout<<str;
    
        return min;
    }