[LeetCode]38. Count and Say
来源:互联网 发布:东莞农村商业银行网络 编辑:程序博客网 时间:2024/05/29 07:39
Description
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
Example1:
Input: 1
Output: “1”Example2:
Input: 4
Output: “1211”
Discussion
第一个数字为“1”,第二个数字是第一个数字的读法“一个1”或“11”,第三个数字是第二个数字的读法“两个1”或“21”,以此类推……
知道了规律后,我们就可以确定算法了。每一个字符串都是根据上一个字符串来生成的。这就转变成了一个计数问题。我们只需要遍历一遍,每次检查当前字符是否和上一个字符相同,相同的话就把计数器加一,不同的话就在新的字符串中添加相应的信息。
算法的时间复杂度为O(n^2)。
C++ Code
class Solution {public: string countAndSay(int n) { vector<string> answer; //保存结果,answer[i-1]保存第i个结果 answer.push_back("1"); for(int i = 1; i < n; i++) { string tmp = answer[i - 1]; //记录上一次的字符串 string new_answer = ""; //新字符串的结果 int count = 1; for(int j = 1; j <= tmp.length(); j++) { //遍历到tmp末尾后一个的时候,就把前面的数字加到answer中,并跳出 if(j == tmp.length()) { new_answer = new_answer + to_string(count) + tmp[j - 1]; break; } //判断当前字符是否和前一个字符相同,如果相同则计数器加一,否则把前一段相同的字符加入到answer中。 if(tmp[j] == tmp[j - 1]) { count ++; } else { new_answer = new_answer + to_string(count) + tmp[j - 1]; count = 1; } } answer.push_back(new_answer); } return answer[n - 1]; }};
阅读全文
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
- python3.6.3+opencv3.3.0学习笔记五--动态人脸捕获
- PortAudio+webrtc+lame实现采集降噪增益mp3
- UnicodeDecodeError: 'ascii' codec can't decode byte 0xe7 in position 0: ordinal not in range(128)错误解
- 使用Tomcat发布一个WEB项目(web,tomcat概述)
- 使用预处理器进行调试
- [LeetCode]38. Count and Say
- 集合扩展方法、委托的运算、事件
- 2017.10.11一试
- ccf 相反数
- linux 添加第三方软件快捷方式
- 在roslaunch中通过rosbag运行bag文件
- php curl 发送post/get请求
- linux学习笔记(1)
- webService(axis2)报错解决