代码
#include <iostream>
#include <sstream>
using namespace std;
int strToInt(string s) {
stringstream ss;
int t;
ss<<s;
ss>>t;
return t;
}
int main() {
string s1, s2;
getline(cin, s1);
getline(cin, s2);
if(!s1.compare("C")) {
char ans[1001];
s2 = s2 + "0"; //最后补一个非法元素,利于下面的循环统一形式
char ch = s2.at(0);
int count = 1;
for(int i=1; i<s2.length(); i++) {
if(s2.at(i)==s2.at(i-1)) {
count++;
} else {
if(count==1) {
cout<<s2.at(i-1);
} else {
cout<<count<<s2.at(i-1);
}
ch = s2.at(i);
count = 1;
}
}
cout<<endl;
} else {
int pos = 0;
string ans = "";
for(pos=0; pos<s2.length(); pos++) {
string count = "";
while(s2.at(pos)>='0' && s2.at(pos)<='9') {
count += s2.at(pos);
pos++;
}
if(!count.compare("")) {
cout<<s2.at(pos);
} else {
int count1 = strToInt(count);
char next = s2.at(pos);
for(int i=0; i<count1; i++) {
cout<<next;
}
}
}
cout<<endl;
}
return 0;
}
注解
1、对字符串最好不要用"+"操作。本题采取的办法是一个字符一个字符进行输出。也可采用char[]代替string的方式。
2、字符串压缩,主要是找到每个字符串出现的次数。因此主要操作是比较当前字符与前一个字符。而字符串解压主要是看当前读到的字符是不是数字,如果是数字则要继续往下读,直到读到字符。