题目
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
21
1211
111221
312211
13112221
1113213211
31131211131221
- 13211311123113112211
需要找出第N个序列,本来一直想找规律,结果找不到,只有最慢的方法,依次解析字符,从1到第N个依次计算,最后得出结果。
C代码如下,已通过。
char* countAndSay(int n) {
char * ans=(char *)malloc(sizeof(char)*100000);
ans[0]='1';
ans[1]='\0';
for(int i=1;i<n;i++)
{
char *temp=(char *)malloc(sizeof(char)*100000);
int k=0;
while(ans[k]!='\0')
{
temp[k]=ans[k];
k++;
}
temp[k]='\0';
//printf("temp:%s\n",temp);
char left=' ';
int num=1,ansLength=0;
for(int j=0;j<k;j++)
{
if(temp[j]==left)
{
num++;
}
else
{
if(left!=' ')
{
ans[ansLength]=num+'0';
ansLength++;
ans[ansLength]=left;
ansLength++;
num=1;
}
left=temp[j];
}
}
ans[ansLength]=num+'0';
ansLength++;
ans[ansLength]=left;
ansLength++;
ans[ansLength]='\0';
//printf("ans:%s\n",ans);
free(temp);
}
return ans;
}
网友评论