1078 字符串压缩与解压 (20 分)

87 阅读1分钟

1078 字符串压缩与解压 (20 分)

题目链接

算法分析

分两种情况进行处理就好,也没什么特别的,主要就是在一些代码的处理上存在细节,可以简化代码。

代码实现

#include<bits/stdc++.h>
using namespace std;

int main(){
	char is, k;
	string s;
	cin>> is;
	k = getchar();//读入换行符
	getline(cin, s);
	int len = s.size();
	if(is == 'C')
		for(int i = 0; i < len; ++ i){
			int cnt = 1;
			while(s[i + 1] == s[i]){
				i ++;
				cnt ++;
			}
			if(cnt != 1)
				printf("%d%c", cnt, s[i]);
			else
				printf("%c", s[i]);
		}
	else
		for(int i = 0; i < len; ++ i){
			if(isdigit(s[i])){
				int sum = s[i] - '0';
				while(isdigit(s[i + 1])){//数字如果是两位数及以上
					i ++;
					sum = sum * 10 + s[i] - '0';
				}
				for(int j = 1; j <= sum; ++ j)
					printf("%c", s[i + 1]);
				i ++;
			}
			else	printf("%c", s[i]);
		}
	return 0;
}