38. Count and Say

一、题目描述

​输入整数n,记录出现字符的个数并输出对应的字符串。例如

n=1,str=1

n=2,str=11(1个1)

n=3,str=21(2个1)

n=4,str=1211(1个2,1个1)

以此类推

二、思路

1.n=1时,输出字符串1,并初始化字符串

2.n=2开始,循环并记录字符出现的个数

三、C代码



char * countAndSay(int n){
    if(n == 1)
    {
        return "1";    //n=1
    }

    //n=1,初始化指针str,并指向字符串"1"
    char *str = malloc(sizeof(char) * 3);
    str[0] = '1';
    str[1] = '\0';

    //n=2,开始循环
    for(int i = 2; i <= n; i++)
    {
        unsigned int length = strlen(str);
        char *temp = malloc(sizeof(char) * length * 3);    //防止溢出
        memset(temp, 0, sizeof(char) * length * 3);
        int count = 1, cur = 0;
        for(int index = 1; index < length; index++)
        {
            if(str[index] == str[index-1])    //和前一个字符相同,则计数
            {
                count++;
            }
            else
            {
                temp[cur++] = count + '0';
                temp[cur++] = str[index-1];
                count = 1;
            }
        }
        temp[cur++] = count + '0';
        temp[cur] = str[length - 1];
        free(str);
        str = temp;
    }
    return str;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值