ZOJ-2240 Run Length Encoding

Run Length Encoding


Time Limit: 2 Seconds      MemoryLimit: 65536 KB


Your task is towrite a program that performs a simple form of run-length encoding, asdescribed by the rules below.

Any sequence ofbetween 2 to 9 identical characters is encoded by two characters. The firstcharacter is the length of the sequence, represented by one of thecharacters 2 through 9. The second character is the value of the repeatedcharacter. A sequence of more than 9 identical characters is dealt with byfirst encoding 9 characters, then the remaining ones.

Any sequence ofcharacters that does not contain consecutive repetitions of any characters isrepresented by a 1 characterfollowed 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.

InputSpecification

The input consistsof letters (both upper- and lower-case), digits, spaces, and punctuation. Everyline is terminated with a newline character and no other characters appear inthe input.

OutputSpecification

Each line in theinput is encoded separately as described above. The newline at the end of eachline is not encoded, but is passed directly to the output.

Sample Input

AAAAAABCCCC

12344

Sample Output

6A1B14C

11123124


#include <stdio.h>
#include <string.h>

int main()
{
	char str[1000];
	int i, len, j, t;
	char count[3000][2];
	while(gets(str) != NULL) {
		len = strlen(str);
		for(i = 0, t = 0; i < len;) {
			j = i;
			while(j < len && str[i] == str[j] && j-i < 9) {
				j++;
			}
			count[t][0] = str[i];
			count[t++][1] = j-i+'0';
			i = j;
		}
		for(i = 0; i < t;) {
			if(count[i][1] > '1') {
				printf("%c%c", count[i][1], count[i][0]);
				i++;
			} else {
				j = i;
				printf("1");
				while(j < t && count[j][1] == '1') {
					printf("%c", count[j][0]);
					if(count[j][0] == '1') {
						printf("1");
					}
					j++;
				}
				printf("1");
				i = j;
			}
		}
		printf("\n");
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值