Run Length Encoding(行程长度压缩)
Run Length Encoding
Description
Your task is to write a program that performs a simple form of run-length encoding, as described by the rules below.
Any sequence of between 2 to 9 identical characters is encoded by two characters. The first character is the length of the sequence, represented by one of the characters 2 through 9. The second character is the value of the repeated character. A sequence of more than 9 identical characters is dealt with by first encoding 9 characters, then the remaining ones.
Any sequence of characters that does not contain consecutive repetitions of any characters is represented by a 1 character followed by the sequence of characters, terminated with another 1. If a 1 appears as part of the sequence, it is escaped with a 1, thus two 1 characters are output.
Input
The input consists of letters (both upper- and lower-case), digits, spaces, and punctuation. Every line is terminated with a newline character and no other characters appear in the input.
Output
Each line in the input is encoded separately as described above. The newline at the end of each line is not encoded, but is passed directly to the output.
Sample Input
AAAAAABCCCC
12344
Sample Output
6A1B14C 11123124
题意:对于一行输入的字符串
1:重复字符构成的子字符串,用数字+字符表示缩短其长度,长度超过9则先用9+字符表示一段字符(剩余长度同理)
例如:AAAAAA 输出 6A
2:非重复字符构成的子字符,子字符串首尾均多输出一个'1',并且对于子字符串中的'1',输出为'11'
例如: B 输出 1B1 123 输出 11231
AC Code:
#include<iostream>
#include<sstream>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<ctype.h>
#include<map>
#include<vector>
#include<stack>
#include<queue>
#include<set>
#include<list>
#define mod 998244353
#define Max 0x3f3f3f3f
#define Min 0xc0c0c0c0
#define mst(a) memset(a,0,sizeof(a))
#define f(i,a,b) for(int i=a;i<b;i++)
using namespace std;
typedef long long ll;
const int maxn=10005;
int main(){
ios::sync_with_stdio(false);
int n;
char str[maxn];
while(gets(str)){ //输入包含空格
int index, i = 0;
int len = strlen(str);
int flag = 0; //标识符
while(1){
index = 1;
while(str[i] == str[i+index] && index < 9 && i < len){
index++;
}
if(i == len){
if(flag == 1){
printf("1");
}
break;
}
else if(index == 1){
if(flag == 0){ //判断是否为新的非重复字符构成的子字符串
printf("1");
flag = 1;
}
if(str[i] == '1'){ //非重复子字符串中的'1'输出均为'11';
printf("1");
}
printf("%c", str[i]);
}
else{
if(flag == 1){ //如果一个重复子字符串前面是一个非重复子字符串,输出一个'1'
printf("1");
flag = 0;
}
printf("%d%c", index, str[i]);
}
i += index;
}
printf("\n");
}
return 0;
}