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 }