原题目不是很好的可以将题目的意思读懂。之后查了资料才发现题目的真正含义:
1:1
2:11(1个1)
3:21(2个1)
4:1211(1个2,1个1)
5:111221(1个1,1个2,2个1)
6:312211(3个1,2个2,1个1)
……
如果这样翻译这道题目就是比较容易做出来的。
思想我觉得也不是很麻烦。就是需要不停的遍历。如果要求出第n个数字。那么 n-1的遍历,要知道n-1的就需要n-2的,一直到第一个。而每次遍历的时候就是需要记录下有几个几并将其重新放到数组中进行下一次的遍历即可。
代码:
void ContSay(char *str1,char *str2){
int count,i,j;
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 = 0; i<n ; i++) {
ContSay(str2,str1);
strcpy(str2,str1);
}
return str2;
}