leetcode 38. Count and Say
来源:互联网 发布:unity3d与ar 编辑:程序博客网 时间:2024/05/29 18:10
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"
or11
.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的,已经反馈了,但不知改了没。
0 0
- [LeetCode]38.Count and Say
- LeetCode --- 38. Count and Say
- LeetCode 38.Count and Say
- [Leetcode] 38. Count and Say
- 38. Count and Say LeetCode
- Leetcode 38. Count and Say
- leetcode 38. Count and Say
- [leetcode] 38. Count and Say
- LeetCode-38.Count and Say
- LeetCode *** 38. Count and Say
- leetcode 38. Count and Say
- LeetCode-38. Count and Say
- LeetCode 38. Count and Say
- LeetCode 38. Count and Say
- Leetcode - 38. Count and Say
- LeetCode 38. Count and Say
- Leetcode 38. Count and Say
- LeetCode 38. Count and Say
- bzoj 1610: [Usaco2008 Feb]Line连线游戏
- c++第三次实验
- Symbol数据类型
- 【USACO题库】2.3.3 Zero Sum和为零
- Java命名规范
- leetcode 38. Count and Say
- 博为峰Java技术文章 ——JavaSE Swing 文件选取器JFileChooser(1)
- LeetCode-algorithms 34. Search for a Range
- 第一只爬虫---糗事百科
- 【划重点】第一篇博客
- Consul实践之Consul是什么
- (蓝桥杯模拟)1.算年龄 & 4.字符串比较(填空) & 5.还款计算
- 位图的实现
- 深度学习之《社交网络问答系统-问题重复检测任务》实现