首页 > 编程语言 > 详细

每日LeetCode - 38. 外观数列(C语言)

时间:2021-05-13 19:37:08      阅读:12      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

C语言

//递归
char * countAndSay(int n){
    char *say = (char*)malloc(sizeof(char)*5000);
    
    if (n>30||n<1)
        return NULL;
    
    if (n == 1){
        free(say);
        return "1";
    }
    else{
        char *s = countAndSay(n-1);
        int pcounts=0, pnumber=1;
        for(int i=0;s[i]!=\0;i++){
            if (i==0){
                say[pnumber]=s[i];
                say[pcounts]=1;
            }
            else if (s[i-1]==s[i]){
                say[pcounts]++;
            }
            else{
                pnumber+=2;
                pcounts+=2;
                say[pcounts]=1;
                say[pnumber]=s[i];
            }
        }
        say[pnumber+1]=\0;
        return &say[0];
    }
}
//双指针
//https://leetcode-cn.com/problems/count-and-say/solution/38-wai-guan-shu-lie-shuang-zhi-zhen-by-yiluolion/
char * countAndSay(int n){    
    if (n>30||n<1)
        return NULL;

    char *cur = (char*)malloc(sizeof(char)*5000);
    char *pre = (char*)malloc(sizeof(char)*5000);
    int p, i, start, end;

    cur[0]=1;
    cur[1]=\0;
    i=1;
    while (i<n){
        strcpy(pre, cur); //why have to use strcpy(pre, cur)? and cannot be pre=cur?
        *cur="";
        p=0;
        start=0;
        end=0;
        while(pre[end]!=\0){
            while (pre[end]!=\0&&pre[start]==pre[end])
                end++;
            cur[p++]=end-start+0;
            cur[p++]=pre[start];
            start=end;
        } 
        cur[p]=\0;  
        i++;
    }
    return cur;
}

 

每日LeetCode - 38. 外观数列(C语言)

原文:https://www.cnblogs.com/vicky2021/p/14765329.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!