1 #include<iostream>
2 #include<string.h>
3 #include<string>
4 #include<cstring>
5 #include<sstream>
6 using namespace std;
7 /*
8 问题检查函数
9 参数:输入的字符串
10 返回:BOOL
11 真表示为编码问题
12 假表示为解码问题
13 */
14 bool check(string str){
15 bool ok=true;
16 for(int i=str.length()-1;i>=0;i--){
17 if(str[i]>='0' && str[i]<='9'){
18 ok=false;
19 break;
20 }
21 }//遍历看字符串中是否含有数字
22 return ok;
23 }
24 /*
25 编码函数
26 参数:待编码字符串
27 返回:无
28 */
29 void bian(string str){
30 str+='0';//给待编码的字符串加一个结束位’0‘
31 string new_str="";//编码后的字符串
32 int slen=str.length();
33 char pre=str[0];//标记当前计算重复的字符
34 int renum=0;//当前重复的个数
35 for(int i=0;i<slen;i++){
36 if(str[i]==pre){//如果重复就继续累加
37 renum++;
38 }else{//否则将累加度和自符存入新的字符串中并更新字符和重复度
39 char *temp=new char;
40 sprintf(temp,"%d",renum);
41 new_str+=temp;
42 new_str+=pre;
43 renum=1;
44 pre=str[i];
45 }
46 }
47 str=str.substr(0,slen-1);
48 cout<<"**********************************************\n";
49 cout<<"* 你想的是把原来的数据编码,对吧?结果如下:\n";
50 cout<<"* "<<str<<" ---> "<<new_str<<'\n';
51 cout<<"* 转换前长度为: "<<str.length()<<'\n';
52 cout<<"* 转换后长度为: "<<new_str.length()<<'\n';
53 cout<<"* 转换率为 : "<<new_str.length()/(str.length()*1.0)<<"\n";
54 cout<<"**********************************************\n\n";
55 }
56 /*
57 解码函数
58 参数:待解码字符串
59 输出:无
60 */
61 void jie(string str){
62 istringstream in(str);//使用流操作
63 int num;char s;
64 string new_str="";
65 while(in>>num>>s){
66 while(num--)new_str+=s;
67 }
68 cout<<"**********************************************\n";
69 cout<<"* 你想的是把原来的数据解码,对吧?结果如下:\n";
70 cout<<"* "<<str<<" ---> "<<new_str<<'\n';
71 cout<<"* 解码前长度为: "<<str.length()<<'\n';
72 cout<<"* 解码后长度为: "<<new_str.length()<<'\n';
73 cout<<"* 解码率为 : "<<new_str.length()/(str.length()*1.0)<<"\n";
74 cout<<"**********************************************\n\n";
75 }
76 int main(){
77 string str;
78 while(getline(cin,str)){
79 if(check(str)){
80 bian(str);
81 }else{
82 jie(str);
83 }
84 }return 0;
85 }