[leetcode]Count and Say (伯爵说 C语言实现)

Count and Say
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.
Given an integer n, generate the nth sequence.

Note: The sequence of integers will be represented as a string.
题意:伯爵说,
1读为“一个1”输出11
11读为“两个1”输出21
………..
给定一个n,输出第n个字符串序列
Notes:整型序列用字符串表示。
解题思路:这涉及的知识点是字符串的操作,字符串转整型,还有就是细节问题,对最后一个字符的操作,对相同字符的统计并作为下一个字符串的字符。
C语言实现代码:

/**
 * 解题思路:涉及到字符串的简单操作,需要获取字符串中相同字符的个数并作为下一个字符串的字符
 * 输入的n代表去第几个字符串输出,这同时也需要求出前面字符串的值,就行Fibonacci数列一样,求后一个字符串需要知道前一个字符串
 */
void CountSay(char *str1, char *str2){
    int count, i, j;
    count = 1;
    j = i = 0;
    while(*(str1+i+1) != '\0'){
        if(*(str1+i) == *(str1+i+1)){
            i++;
            count++;
        }else{
            *(str2 + j++) = count + '0';
            *(str2 + j++) = *(str1+i);
            i++;
            count = 1;
        }
    }
    *(str2 + j++) = count + '0';
    *(str2 + j++) = *(str1+i);
}

char *countAndSay(int n) {
    char *str1, *str2;
    int i;
    str1 = (char *)malloc(9999*sizeof(char));//初始化数组大小
    str2 = (char *)malloc(9999*sizeof(char));
    memset(str1, 0 ,9999);
    memset(str2, 0, 9999);
    strcpy(str2, "1");
    for(i = 1; i <n; i++){
        CountSay(str2, str1);
        strcpy(str2,str1);
    }
    return str2;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值