leetcode 38. Count and Say

leetcode 38. Count and Say  计数和报数(c语言实现)

Description

The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...

1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.

题目的意思:

n=1,为 1

n=2,表示n=1有一个1,结果就为11

n=3,表示n=2有2个1,结果就为21

n=4,表示n=3有1个2和1个1,结果就为1211

n=5,表示n=4有1个1,1个2,2个1,结果就为111221

n=6,表示n=5有3个1,2个2,1个1,结果就为312211

以此类推。

char* countAndSay(int n) {
    char *precountAndSay;
    int length, i, j = 0, count = 1;
    char * retStr;
    if(n == 1) 
    {
        retStr = (char*)malloc(sizeof(char) * 2);//多的一个存'\0'
        retStr[j++] = '1';
    }
    else if(n == 2){
        retStr = (char*)malloc(sizeof(char) * 3);
        retStr[j++] = '1';
        retStr[j++] = '1';
    }
    else if(n == 3) 
    {
        retStr = (char*)malloc(sizeof(char) * 3);
        retStr[j++] = '2';
        retStr[j++] = '1';
    }
    if(n > 3)
    {
        precountAndSay= countAndSay(n-1);//找到上一次的串,递归法
        length = strlen(precountAndSay);//上次串的长度
        retStr = (char*)malloc(sizeof(char) * (2 * length + 1));//最差的情况,分配的内存是length的2倍加1
        for(i = 1; i < length; i++)
        {
            if(precountAndSay[i-1] == precountAndSay[i])//相等,数有多少个这样的数,存于count
            {
                count ++;
                continue;
            }else{
                retStr[j++] = count + '0';//将count转化为1-9的字符
                retStr[j++] = precountAndSay[i - 1];//存发现count计数后出现不同时的前一个值
                count = 1;
            }
        }
        //处理最后一个字符
        retStr[j++] = count + '0';
        retStr[j++] = precountAndSay[i - 1];
            
        
    }
    retStr[j] = '\0';//转成字符串
    return retStr;
}

这个题目,run有个bug,无论输入多少,官方给的期待的值始终为null。但submit solution是Accepted的,已经反馈了,但不知改了没。




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值