leetcode #38 in cpp
来源:互联网 发布:php学生管理系统 编辑:程序博客网 时间:2024/06/05 23:41
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.
Solution:
for 1 to n:
Set current string = "";
Given a string, count the frequency of every unique number. Then append the (frequency in string) + (the number in string) to current string.
Code:
class Solution {public: string countAndSay(int n) { string s = "1"; return count_and_say(s,n); } string count_and_say(string s, int n){ if(n == 1) return s; vector<int> count;//count the frequencies of the unique numbers vector<char> real_num;//record the unique numbers in the string int temp_count = 0; for(int i = 0; i < s.length(); i ++){ if(i==0 || s[i] == s[i-1]) temp_count ++;//if the same or it is the head of the string, count + 1 else{ count.push_back(temp_count);//if not the same, we are done with this number.record its count real_num.push_back(s[i-1]);//record this number temp_count = 1; } } count.push_back(temp_count); real_num.push_back(s[s.length() - 1]); string res = ""; for(int i = 0; i < count.size(); i++){ res += '0' + count[i];//say count first res += real_num[i];//say the number } return count_and_say(res,n-1); }};
0 0
- leetcode #38 in cpp
- leetcode #12 in cpp
- Leetcode #13 in cpp
- Leetcode #14 in cpp
- leetcode %15 in cpp
- leetcode #16 in cpp
- leetcode #17 in cpp
- leetcode #18 in cpp
- leetcode #20 in cpp
- leetcode #21 in cpp
- leetcode #22 in cpp
- leetcode #23 in cpp
- leetcode #24 in cpp
- leetcode #25 in cpp
- leetcode #26 in cpp
- leetcode #27 in cpp
- leetcode #28 in cpp
- leetcode #29 in cpp
- 使用ListActivity优化功能
- leetcode #37 in cpp
- java.lang.NoClassDefFoundError: javax/servlet/jsp/jstl/core/Config
- java入门教程-5.6Java泛型详解,通俗易懂只需5分钟
- Android中SQLite以及ContentProvider自我学习、理解、失败之总结
- leetcode #38 in cpp
- java入门教程-5.7java泛型通配符和类型参数的范围
- java入门教程-6.1Java异常处理基础
- java入门教程-6.2Java异常类型
- java入门教程-6.3Java未被捕获的异常
- java入门教程-6.4Java try和catch的使用
- java入门教程-6.5Java 多重catch语句的使用
- java入门教程-6.6Java try语句的嵌套
- java入门教程-6.7Java throw:异常的抛出