leetcode-38 count and say

题目的意思有点迷惑,正确的理解如下:

At the beginning, I got confusions about what is the nth sequence. Well, my solution is accepted now, so I'm going to give some examples of nth sequence here. The following are sequence from n=1 to n=10:

 1.     1
 2.     11
 3.     21
 4.     1211
 5.     111221 
 6.     312211
 7.     13112221
 8.     1113213211
 9.     31131211131221
 10.   13211311123113112211

From the examples you can see, the (i+1)th sequence is the "count and say" of the ith sequence!

从discuss中发现了一种很好的算法:

char *countAndSay(int n) {
    int i,j,k;
    char tmp[10240];
    char res[10240] = "1";
    for(i = 2; i <= n; i++){
		int count = 1;
		char digit = res[0];
		k = 0;
		for(j = 1; j < strlen(res); j++){
			if(res[j] == digit)
				count++;
			else{
				tmp[k++] = count + '0';
				tmp[k++] = digit;
				digit = res[j];
				count = 1;
			}
		}
		tmp[k++] = count + '0';
		tmp[k++] = digit;
		strncpy(res,tmp,k);
    }
    return res;
}

注意产生的串会很长的,所以数组tmp和res的长度要足够用(1024不够,如果使用1024,则一直runtime error)

char str[1024] = "1";
则strlen(str)的值为1;

sizeof(str)的值为1024;



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值