现在的位置: 首页 > 综合 > 正文

poj1782Run Length Encoding(题目难以看懂,也有一些坑)

2018年02月22日 ⁄ 综合 ⁄ 共 1811字 ⁄ 字号 评论关闭

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
题目意思:看了老半天题目意思就是不怎么看明白,问了别人才知道。给出一串字符,只要是字符都可以输入,包括空格,如果有连续相同字符,连续的长度超过9,那么前面9个看成一段,后面是另一段,那么就输出长度和这个字符,如果没连续的字符就看成一整块,在输出这一整块时前后都有一个1,作为与其他块隔断。如果一整块中有字符1,把这个1字符变成两个字符1.
注意:有连续长度大于等于2的字符1时,这个字符不用变成两个1;如果只是一个回车,也就是字符串长度为0时,只输出换行符。
#include<stdio.h>
#include<string.h>
int main()
{
    char str[100000];
    int k,sim,one,len,i;
    while(gets(str))
    {
        k=1; one=0; sim=0; i=0;
        len=strlen(str);
        if(len==0) {printf("\n");continue;}
        if(str[0]=='1') one=1;
        if(str[0]==str[1]) sim=1;
        if(sim==0) printf("1");
        while(i<len)
        {
            if(sim==1)
            {
                if(str[i]==str[i+1]&&k<9) k++;
                else {
                    printf("%d",k);
                    printf("%c",str[i]);
                    k=1; sim=0; one=0;
                    if(str[i+1]=='1') one=1;
                    if(str[i+1]==str[i+2]||i+1==len) sim=1;
                    if(sim==0&&i+1<len)
                        printf("1");
                }
            }
            else
            {
                if(one) printf("1"); one=0;
                printf("%c",str[i]);
                if(str[i+1]=='1') one=1;
                if(str[i+1]==str[i+2]||i+1==len)
                sim=1,k=1,printf("1");
            }
            i++;
        }
        printf("\n");
    }
}

抱歉!评论已关闭.