[アルゴリズム]プログラマ文字列圧縮
15374 ワード
このブログは、非商業的な学業のためにのみ投稿されています.
比較文字の数が固定されているので、簡単に言えば、1個、2個、…(文字列の長さ/2)単語を順番にカットして比較すればいいです. 最初は文字列を最適に圧縮すべきだと考えられていたが、圧縮された標準文字列の数は固定されているため、容易になった. 分析によって解決された. ジェネレータを使用して文字列を切り取り、次のコードはsubstrを使用して切り取り、Back Junのような環境で速度比較を行いたいと思います.
1.問題分析
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.学習の達人のコード
#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;
}
Reference
この問題について([アルゴリズム]プログラマ文字列圧縮), 我々は、より多くの情報をここで見つけました https://velog.io/@fortice/알고리즘-프로그래머스문자열-압축テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol