题目的意思有点迷惑,正确的理解如下:
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;