#include <iostream>
using namespace std;
#include <string>
class Solution {
public:
string compressString(string S) {
//字符掃描
char temp = S[0];
//計數
int count = 1;
//輸出字符串
string out;
//遍歷整個字符串
for (int i = 0; i <= S.length(); ++i)
{
if (i == 0)
{
out += S[0];
continue;
}
if (S[i] == temp)
{
count++;
}
else
{
out += to_string(count);
count = 1;
temp = S[i];
out += temp;
}
}
if (out.length() <= S.length())
{
return out;
}
else
{
return S;
}
}
};
//測試代碼
int main()
{
Solution method;
string str = "abbccd";
string out = method.compressString(str);
cout << out << endl;
system("pause");
}
(C++)壓縮字符串
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.