解题思路和代码:
/*************************************************************************
> File Name: compress.cpp
> Author: 念念
> Mail: 2845906049@qq.com
> Created Time: 2021年08月27日 星期五 9时42分49秒
> Function: 字符串压缩。利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。
比如,字符串aabcccccaaa会变为a2b1c5a3。
若“压缩”后的字符串没有变短,则返回原先的字符串。你可以假设字符串中只包含大小写英文字母(a至z)
************************************************************************/
#include <iostream>
#include <string>
using namespace std;
//效果:84.03% 76.65%
string compress(string str)
{
if(str.empty())return str;
int count = '1';
string ans;
for(int i = 0; i < str.length(); i += count)
{
count = 1;
int j = i+1;
while(str[j] == str[i])
{
count++;
j++;
}
ans += str[i] + to_string(count);
}
return ans.length() < str.length() ? ans : str;
}
int main()
{
cout << compress("aaaaabbbcdee");
return 0;
}