HDU1020 ZOJ2478 Encoding

问题链接:HDU1020 ZOJ2478 Encoding入门练习题,用C语言编写程序。

这是一个输入流处理的程序,最佳方案是一边读入一边处理。

这里给出两个C语言程序,有个比较。一个是用gets()函数把每行的字符串读入到字符数组中再行处理;另外一个是用getchar()函数逐个读入字符处理。 

AC的C语言程序(正解)如下:

/* HDU1020 ZOJ2478 Encoding */

#include <stdio.h>

#define MAXN 10000


int main(void)
{
    int n, count;
    char in, c;

    scanf("%d", &n);
    getchar();
    while(n--) {
        count = 0;
        c = '\0';
        for(;;) {
            in = getchar();

            if(in == '\n')
                break;

            if(in != c) {
                if(count != 0) {
                    if(count == 1)
                        putchar(c);
                    else
                        printf("%d%c", count, c);
                }
                c = in;
                count = 1;
            } else
                count++;
        }
        if(count > 0) {
            if(count == 1)
                putchar(c);
            else
                printf("%d%c", count, c);
        }
        printf("\n");
    }

    return 0;
}

另外一个版本,AC的C语言程序如下:
/* HDU1020 Encoding */

#include <stdio.h>
#include <stdlib.h>

#define MAXN 10000


int main(void)
{
    int n, count;
    char s[MAXN+1], c, *p;

    gets(s);
    n = atoi(s);
    while(n--) {
        gets(s);

        count = 0;
        c = '\0';
        p = s;
        while(*p) {
            if(*p != c) {
                if(count != 0) {
                    if(count == 1)
                        printf("%c", c);
                    else
                        printf("%d%c", count, c);
                }
                c = *p;
                count = 1;
            } else
                count++;
            p++;
        }
        if(count > 0) {
            if(count == 1)
                printf("%c", c);
            else
                printf("%d%c", count, c);
        }
        printf("\n");
    }

    return 0;
}

 

转载于:https://www.cnblogs.com/tigerisland/p/7564570.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值