![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/8f4bf89da74854bb93dc69e442d5ae49.png)
柳神代码
#include <iostream>
using namespace std;
int main() {
char t;
cin >> t;
getchar();
string s, num;
getline(cin, s);
int cnt = 1;
if (t == 'D') {
for (int i = 0; i < s.length(); i++) {
if (s[i] >= '0' && s[i] <= '9') {
num += s[i];
} else {
if (num.length() > 0) cnt = stoi(num);
while(cnt--) cout << s[i];
cnt = 1;
num = "";
}
}
} else if (s.length() != 0) {
char pre = s[0];
for (int i = 1; i < s.length(); i++) {
if (s[i] == pre) {
cnt++;
} else {
if (cnt >= 2) cout << cnt;
cout << pre;
cnt = 1;
pre = s[i];
}
}
if (cnt >= 2) cout << cnt;
cout << pre;
}
return 0;
}
二刷
#include<iostream>
#include<string>
using namespace std;
void compression(string s){
int num=0;
for(int i=0;i<s.size();){
if(s[i+1]==s[i]) {
num=0;
while(s[i]==s[i+num]) num++;
cout<<num<<s[i];
i+=num;
}else {cout<<s[i];i++;};
}
}
void decompression(string s){
for(int i=0;i<s.size();){
if(isdigit(s[i])){
string num;
int x=i;
while(isdigit(s[x])){
num+=s[x];
x++;
}
for(int j=0;j<stoi(num);j++) cout<<s[x];
int len=num.size();
i+=(len+1);
}else {
cout<<s[i];
i++;
}
}
}
int main(){
char c;
cin>>c;
string s;
getchar();
getline(cin,s);
if(c=='C') compression(s);
else decompression(s);
return 0;
}
我的代码
#include<iostream>
#include<map>
#include<string>
using namespace std;
string num;
int cnt=1;
void jieya(string s) {
for (int i = 0; i < s.length(); i++) {
if (s[i] >= '0' && s[i] <= '9') {
num += s[i];
} else {
if (num.length() > 0) cnt = stoi(num);
while(cnt--) cout << s[i];
cnt = 1;
num = "";
}
}
}
string yasuo(string s) {
string x;
for (int i = 0; i < s.length(); i += 0) {
int j = i + 1,count = 1;
while (s[j] == s[i]) count++, j++;
if (count == 1) {
x += (s[i]);
i += count;
}else {
x += (to_string(count) + s[i]);
i += count;
}
}
return x;
}
int main() {
char c;
cin >> c;
if (c == 'C') {
getchar();
string temp;
getline(cin, temp);
cout << yasuo(temp) << endl;
}
else {
getchar();
string temp;
getline(cin, temp);
jieya(temp);
}
return 0;
}