[leetcode]50 Count and Say
2015-04-07 16:03
369 查看
题目链接:https://leetcode.com/problems/count-and-say/
Runtimes:12ms
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.
Runtimes:12ms
1、问题
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.
2、分析
数并且说出来,题目简单,请看英文实例~3、小结
严谨的思路~4、实现
class Solution { public: string change(int n) { string s = ""; if (n >= 0 && n <= 9) return s += (n + '0'); while (n > 0) { s += (n % 10) + '0'; n /= 10; } int i = 0, j = s.length() - 1; while (i < j) { char c = s[i]; s[i] = s[j]; s[j] = c; } return s; } string countAndSay(int n) { if (n <= 0) return ""; int i = 1; string result = "1"; while (i < n) { string tmp = ""; int j = 1, start = 0; for (; j < result.length(); ++j) { if (result[j] != result[start]){ tmp = tmp + change(j - start) + result[start]; start = j; } } tmp += change(j - start) + result[start]; result = tmp; //cout << result << endl; ++i; } return result; } };
5、反思
好像可以跑得更快的!待改进~相关文章推荐
- LeetCode No.38 Count and Say
- LeetCode之Count and Say
- [leetcode 38] Count and Say
- leetcode-38 Count And Say
- LeetCode 38 : Count and Say (Java)
- leetcode之路038 Count and Say
- leetcode:Count and Say
- [C++]LeetCode: 20 Count and Say
- [LeetCode 38] Count and Say
- leetcode_38题——Count and Say(string,迭代计数)
- LeetCode Online Judge 题目C# 练习 - Count and Say
- [Leetcode] count and say 计数和说
- [leetcode]Count and Say
- Java for LeetCode 038 Count and Say
- LeetCode(51)- Count and Say
- leetcode-38-Count and Say 基础题
- Leetcode 38 Count and Say
- [leetcode]Count and Say (伯爵说 C语言实现)
- 【LeetCode】C# 38、Count and Say
- Leetcode 38 Count and Say 传说中的递推