題目
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依次展出一個(gè)序列如下所示:
1
11
21
1211
111221
312211
13112221
1113213211
31131211131221
- 13211311123113112211
需要找出第N個(gè)序列,本來一直想找規(guī)律,結(jié)果找不到,只有最慢的方法,依次解析字符,從1到第N個(gè)依次計(jì)算,最后得出結(jié)果。
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;
}