题目: 输入一个字符串,输出对其压缩过的形式。
如输入为:aaabbbccc则输出为3a3b3c;如输入为abbc,则输出为a2bc。
aaabbbccc ----> 3a3b3c
如输入为:aaabbbccc则输出为3a3b3c;如输入为abbc,则输出为a2bc。
aaabbbccc ----> 3a3b3c
abc ----> abc
#include <iostream>
#include <string>
using namespace std;
int main()
{
int cnt = 1;///cnt the number of every char
int pos = 1;
char tmp_A,tmp_B;
string ori_str, sht_str;
string::size_type ori_len;
char c_cnt;
cout<<"input the ori string"<<endl;
cin>>ori_str;
ori_len = ori_str.size();
for (; pos < static_cast<int>(ori_len); ++pos)
{
tmp_A = ori_str[pos - 1];
tmp_B = ori_str[pos];
if (tmp_A != tmp_B && pos != static_cast<int>(ori_len-1))
///没到末尾的时候,AB不同
{
if (cnt == 1)
{
sht_str.push_back(tmp_A);
}
else
{
c_cnt = cnt + '0';
sht_str.push_back(c_cnt);
sht_str.push_back(tmp_A);
cnt = 1;
}
}
else if (tmp_A != tmp_B && pos == static_cast<int>(ori_len-1))
///在末尾,但是A,B不同
{
if (cnt == 1)
{
sht_str.push_back(tmp_A);
}
else
{
sht_str.push_back(cnt);
sht_str.push_back(tmp_A);
cnt = 1;
}
sht_str.push_back(tmp_B);
}
else if (tmp_A == tmp_B && pos != static_cast<int>(ori_len-1))
///不在末尾,AB相同
{
++cnt;
}
else if (tmp_A == tmp_B && pos == static_cast<int>(ori_len-1))
///在末尾,AB相同
{
cnt++;
c_cnt = cnt + '0';
sht_str.push_back(c_cnt);
sht_str.push_back(tmp_A);
}
}
cout<<sht_str;
return 0;
}