#include<iostream>
#include<string>
using namespace std;
int main(){
string s1;
char ch[10005];
int m;
int count1 = 1;
int count2 = 0;
cin>>m;
for(int i = 0; i < m; i++){//依次处理每一行
count2 = 0;
cin>>s1;
if(s1.length() == 1){
cout<<s1<<endl;
continue;
}
for(int j = 1; j < s1.length(); j++){//依次处理每个字符
if(s1[j] == s1[j - 1]){
count1++;
}else {
if(count1 > 1){
count2++;
//ch[count2 - 1] = (char)(count1 + 48);
char temp[10];
sprintf(temp, "%d", count1);//count1的值可能大于个位数
for(int k = 0; temp[k] != '\0'; k++, count2++){
ch[count2 - 1] = temp[k];
}
count2--;
}
count2++;
ch[count2 - 1] = s1[j - 1];
count1 = 1;
}
}
if(count1 != 1){
count2++;
//ch[count2 - 1] = (char)(count1 + 48);
char temp[10];
sprintf(temp, "%d", count1);
for(int k = 0; temp[k] != '\0'; k++, count2++){
ch[count2 - 1] = temp[k];
}
count2--;//很多的count2++与count2--只是为了保持逻辑的直接性
count2++;
ch[count2 - 1] = s1[s1.length() - 1];
count1 = 1;
}else{
count2++;
ch[count2 -1] = s1[s1.length() - 1];
}
ch[count2] = '\0';
cout<<ch<<endl;
}
}hdoj1020简单的字符串处理
最新推荐文章于 2020-05-03 00:27:27 发布
本文介绍了一个简单的字符串压缩算法实现过程,通过遍历输入的字符串,统计连续字符的数量,并将其替换为一个字符加数量的方式输出,如果原始字符重复次数为1,则不进行压缩,直接输出。该算法使用C++编写,涉及基本的字符串处理和字符计数。
213

被折叠的 条评论
为什么被折叠?



