leetcode 38. Count and Say 计数和报数(c语言实现)
Description
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
.
题目的意思:
n=1,为 1
n=2,表示n=1有一个1,结果就为11
n=3,表示n=2有2个1,结果就为21
n=4,表示n=3有1个2和1个1,结果就为1211
n=5,表示n=4有1个1,1个2,2个1,结果就为111221
n=6,表示n=5有3个1,2个2,1个1,结果就为312211
以此类推。
char* countAndSay(int n) {
char *precountAndSay;
int length, i, j = 0, count = 1;
char * retStr;
if(n == 1)
{
retStr = (char*)malloc(sizeof(char) * 2);//多的一个存'\0'
retStr[j++] = '1';
}
else if(n == 2){
retStr = (char*)malloc(sizeof(char) * 3);
retStr[j++] = '1';
retStr[j++] = '1';
}
else if(n == 3)
{
retStr = (char*)malloc(sizeof(char) * 3);
retStr[j++] = '2';
retStr[j++] = '1';
}
if(n > 3)
{
precountAndSay= countAndSay(n-1);//找到上一次的串,递归法
length = strlen(precountAndSay);//上次串的长度
retStr = (char*)malloc(sizeof(char) * (2 * length + 1));//最差的情况,分配的内存是length的2倍加1
for(i = 1; i < length; i++)
{
if(precountAndSay[i-1] == precountAndSay[i])//相等,数有多少个这样的数,存于count
{
count ++;
continue;
}else{
retStr[j++] = count + '0';//将count转化为1-9的字符
retStr[j++] = precountAndSay[i - 1];//存发现count计数后出现不同时的前一个值
count = 1;
}
}
//处理最后一个字符
retStr[j++] = count + '0';
retStr[j++] = precountAndSay[i - 1];
}
retStr[j] = '\0';//转成字符串
return retStr;
}
这个题目,run有个bug,无论输入多少,官方给的期待的值始终为null。但submit solution是Accepted的,已经反馈了,但不知改了没。