Leetcode题解-38. Count and Say
来源:互联网 发布:2014年流行的网络歌曲 编辑:程序博客网 时间:2024/06/03 09:07
Leetcode题解-38. Count and Say
题目
The count-and-say sequence is the sequence of integers with the first five terms as following:
- 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 term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1
Output: “1”
Example 2:
Input: 4
Output: “1211”
题目解释
n=1时,输出字符串“1”;
n=2时,数上次字符串(n=1的字符串)中的数值个数,因为上次字符串有1个1,所以输出“11”(表示1个一);
n=3时,由于上次字符是“11”,有2个1,所以输出“21”(表示2个1);
n=4时,由于上次字符串是21,有1个2和1个1,所以输出“1211”(表示1个2,2个1);
不难看出,这是一个简单的递归题目,也可以化递归为循环
代码
递归写法
class Solution {public: string countAndSay(int n) { string res = "1"; if(n != 1) { n--; while(n--) res = count(res); } return res; } string count(string s){ int count; string res = ""; for(int i = 0; i < s.size(); i++){ count = 1; while((i+1 < s.size()) && s[i] == s[i+1]) { count++; i++; } res += to_string(count) + s[i]; } return res; }};
循环写法
class Solution {public: string countAndSay(int n) { string res = "1"; while (--n) { string cur = ""; for (int i = 0; i < res.size(); i++) { int count = 1; while ((i + 1 < res.size()) && (res[i] == res[i + 1])){ count++; i++; } cur += to_string(count) + res[i]; } res = cur; } return res; }};
阅读全文
0 0
- leetcode题解-38. Count and Say
- Leetcode题解-38. Count and Say
- LeetCode题解:Count and Say
- leetcode题解-686. Repeated String Match && 38. Count and Say
- LeetCode题解:Count and Say解法
- leetcode 题解 || Count and Say 问题
- LeetCode题解——Count and Say
- LeetCode 题解(230) : Count and Say
- [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
- C++ STL 教程
- CSAPP导学
- ZOJ
- MySQL错误信息记录
- 无法获得锁 /var/lib/dpkg/lock
- Leetcode题解-38. Count and Say
- 登录页面通过js判断两次输入的密码是否一致、是否记住密码
- 算法复杂度分析
- 第七节 基本数据类型与String类型的转换
- 102. Binary Tree Level Order Traversal
- NodeManager源码阅读 Thread.setDefaultUncaughtExceptionHandler
- 辗转相除法求最大公约数
- php字符串的有序拆分
- 【Java I/O】如何用Java读写文件