给定一个字符串,只包含小写字母,输出他的压缩存储形式。
aaabbbbcdf
输出为 3a4bcdf
abcdef 1a1b1c1d1e1f
代码1(自己写的):
#include <iostream>
#include <stdio.h>
#include <cstring>
const int maxn = 100;
using namespace std;
char num[maxn];
int main()
{
int cot = 1,i = 1;
scanf("%s",&num); //存在缺陷,scanf只能读取一个单词,遇到空格将返回
//gets(num); //gets缺陷是无法判断输入的字符串是否超过数组长度
while(i<strlen(num))
{
while((i < strlen(num)) && (num[i] == num[i-1]))
{
cot++;
i++;
}
if(cot>1)
printf("%d%c",cot,num[i-1]);
else
printf("%c",num[i-1]);
i++;
cot = 1;
}
if(cot>1)
printf("%d%c",cot,num[i-1]);
else
printf("%c",num[i-1]);
return 0;
}
代码2(西交wrong):
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
using namespace std;
const int maxn = 1005;
typedef pair<int,int> P;
char s[maxn];
int main()
{
cin>>s; //len>=1
int cot=1,i=1; //当前重复串的长度为1
//aaab
while(i<strlen(s))
{
while(i<strlen(s)&&s[i]==s[i-1]) {i++;cot++;}
if(cot>1) printf("%d%c",cot,s[i-1]);
else printf("%c",s[i-1]);
cot=1;
i++;
}
if(cot>1) printf("%d%c",cot,s[i-1]);
else printf("%c",s[i-1]);
return 0;
}
(感谢西交wrong学长提供以上题目练习)