Question1.5:
Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2b1c5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string.遍历的同时计数,当遇到下一个不同的字母时把当前字母和当前计数保存下来
代码:
#include "stdafx.h"
#include <string>
#include <iostream>
#include <sstream>
std::string Compress(std::string);
int main()
{
using namespace std;
string originstr;
cin>>originstr;
cout<<Compress(originstr)<<endl;
return 0;
}
std::string Compress(std::string originstr)
{
using namespace std;
if(originstr.size()==0)
{
return originstr;
}
stringstream res;
char currentchar=originstr[0];
int currentcount=1;
for(int i=1,size=originstr.size();i<size;i++)
{
if(originstr[i]==currentchar)
{
currentcount++;
}
else
{
res<<currentchar<<currentcount;
currentchar=originstr[i];
currentcount=1;
}
}
res<<currentchar<<currentcount;
string result;
res>>result;
if(result.size()<originstr.size())
{
return result;
}
else
{
return originstr;
}
}