LeetCode 38. Count and Say
来源:互联网 发布:centos安装iso文件 编辑:程序博客网 时间:2024/05/21 21:42
这是我在LeetCode中做到的第一道需要用到递归思想的题目,因为自己对递归掌握的不好,这里做个笔记:
题目大意为我们有一个 Count-and-say 的字符串序列,他的第一个元素是‘1’,后一个元素是读前一个而得到的字符串,比如说这里第二个元素就是“11”意思是一个1,那第三个就是“21”,两个1,第四个元素是“1211”,一个2一个1。
这就有点类似斐波那契数列的感觉了,所以我们可以想到应该用递归的思想去做这题。
AC代码如下:
string read(string s){ string say = ""; int count = 1; char now = s[0]; for(int i = 1; i < s.size();i++){ if(s[i] == now){ count++; }else{ char count_char = count + '0'; say = say + count_char + now ; now = s[i]; count = 1; } } char count_char = count + '0'; say = say + count_char + now ; return say;}string countAndSay(int n) { string say = "1"; int i = 1; while(i < n){ say = read(say); i++; } return say;}
countAndSay函数只是控制递归次数的,
主要函数为read函数。
首先分析read函数里的变量的作用:
say是要返回的字符串,now是我当前读到那个数字,count记录有几个now(也就是有几个我正读到的这个数字连在一起)。
然后遍历s字符串,s字符串就是我要得到的Count-And-Say 字符串元素的前一个元素。
now一开始是s的第一个元素,然后遍历从s[1]开始(也就是第二个元素),看s[1]和now是否一样,一样就count++,如果不一样了,那就说明这个now到此为止了,在else中先把count转为char类型,然后把新的这个now的读法接在原本读好的say后面,即say = say + count_char + now。然后这里要把now变成s[i],count变回1,因为我要开始读下一个数字了。
还有就是记得出循环的时候,最后一个now是还没有在else中被加进say里面的,所以出循环还要有一个say = say + count_char + now。
然后return say就可以了。
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
- 利用jsp+uploadify插件实现删除上传到ftp服务器里面的文件
- 杭电 2037 经典贪心
- 插入排序算法(C++实现)
- oracle小知识总结
- jsonp跨域调用
- LeetCode 38. Count and Say
- JavaScript
- AngularJs事件绑定例子
- 1230转换成16进制
- git cherry-pick的使用举例
- 【深入理解JVM】:推荐阅读
- iOS开发之自定义导航栏返回按钮右滑返回手势失效的解决
- OpenGL Frame Buffer管理
- 16进制