[leetcode 38] Count and Say
来源:互联网 发布:大数据产业分析 编辑:程序博客网 时间:2024/06/13 05:08
Question:
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
.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
分析:
可知道后一个数字为前一个数字的Say;
采用递归的方法,求得前一个数字,则可知道当前数字为多少。
代码如下:
<span style="font-size:14px;">class Solution {public: string countAndSay(int n) { string result; string last; int count = 1; if(n == 1) return "1"; if(n == 2) return "11"; last = countAndSay(n-1); for(int i = 1; i < last.size(); ++i){ if(last[i-1] == last[i]){ ++count; if(i == last.size()-1){ switch(count){ case 1: result += "1"; break; case 2: result += "2"; break; case 3: result += "3"; break; case 4: result += "4"; break; case 5: result += "5"; break; case 6: result += "6"; break; case 7: result += "7"; break; case 8: result += "8"; break; case 9: result += "9"; break; } result += last[i-1]; } continue; } else{ switch(count){ case 1: result += "1"; break; case 2: result += "2"; break; case 3: result += "3"; break; case 4: result += "4"; break; case 5: result += "5"; break; case 6: result += "6"; break; case 7: result += "7"; break; case 8: result += "8"; break; case 9: result += "9"; break; } result += last[i-1]; count = 1; if(i == last.size()-1){ result += "1"; result += last[i]; } } } return result; }};</span>
0 0
- [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
- 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
- iOS 汉字下加下划线
- 面下对象(下)三大特征----多态
- JAVA创建XML文件(二)---SAX方式创建XML
- Java基础——Java笔记——StringBuffer类常用方法
- maven中的 dependencies 和 dependencyManagement 的区别
- [leetcode 38] Count and Say
- ORA-01858: 在要求输入数字处找到非数字字符
- container_of()
- Java基础---------------------------------------面向对象---------------------------------------
- IntelliJ IDEA开发golang环境配置
- Java中的享元模式——不可变类的valueOf
- Android登录实例——布局文件
- 项目架构 the clean architecture笔记
- C语言中的offsetof