Given a problem, the count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1被念作“one 1”或者11。 11被念作“two 1s”或者21。 21被念作“one 2, then one 1”或者1211。 给定一个整数n,生成第n个序列。
我已经制定了解决方案,通过扫描每个字符串并相应地生成下一个字符串 时间复杂度为O(nm) 其中m是最大字符串的长度 n是所给定的数字
以下是代码
void countnsay(char str[][1000],int n)
{
int i=1,k;
int j=0;
while(i<=(n-1))
{
//scan str[i-1]
j=0;
k=0; //for building the new string array
while(j<strlen(str[i-1]) )
{
char c=str[i-1][j];
int cnt=1;
while(c==str[i-1][++j])
cnt++;
str[i][k++]=cnt+48;
str[i][k++]=c;
}
str[i][k]='\0';
i++;
}
printf("%s",str[n-1]);
}
int main()
{
int n=5;
char str[1000][1000];
strcpy(str[0],"1");
countnsay(str,n);
return 0;
}
对于这个问题,是否有更好的解决方案? 请提供一些建议/提示。 提前感谢。