一、题目描述
输入整数n,记录出现字符的个数并输出对应的字符串。例如
n=1,str=1
n=2,str=11(1个1)
n=3,str=21(2个1)
n=4,str=1211(1个2,1个1)
以此类推
二、思路
1.n=1时,输出字符串1,并初始化字符串
2.n=2开始,循环并记录字符出现的个数
三、C代码
char * countAndSay(int n){
if(n == 1)
{
return "1"; //n=1
}
//n=1,初始化指针str,并指向字符串"1"
char *str = malloc(sizeof(char) * 3);
str[0] = '1';
str[1] = '\0';
//n=2,开始循环
for(int i = 2; i <= n; i++)
{
unsigned int length = strlen(str);
char *temp = malloc(sizeof(char) * length * 3); //防止溢出
memset(temp, 0, sizeof(char) * length * 3);
int count = 1, cur = 0;
for(int index = 1; index < length; index++)
{
if(str[index] == str[index-1]) //和前一个字符相同,则计数
{
count++;
}
else
{
temp[cur++] = count + '0';
temp[cur++] = str[index-1];
count = 1;
}
}
temp[cur++] = count + '0';
temp[cur] = str[length - 1];
free(str);
str = temp;
}
return str;
}