[Leetcode]Count and Say
2014-03-22 17:23
405 查看
The count-and-say sequence is the sequence of integers beginning as follows:
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
如果有更好更高效的代码,希望大家共享~
本文不详尽或错误之处,请各位不吝言辞,多多指教~谢谢~
作者:Louise http://blog.csdn.net/yupingliu
1, 11, 21, 1211, 111221, ...
1is read off as
"one 1"or
11.
11is read off as
"two 1s"or
21.
21is 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.
如果有更好更高效的代码,希望大家共享~
class Solution { public: string countAndSay(int n) { string seq = "1"; string result = ""; int count = 1; char pre; if(n > 1) { for (int i = 2; i <= n; i++) { pre = ' '; for (int j = 0; j < seq.size(); j++) { if(j + 1 < seq.size() && seq[j + 1] == seq[j]) { count++; } else { pre = seq[j]; result.push_back(count + '0'); result.push_back(pre); count = 1; } } seq = result; result = ""; } return seq; } else if(n == 1) { return "1"; } } };
本文不详尽或错误之处,请各位不吝言辞,多多指教~谢谢~
作者:Louise http://blog.csdn.net/yupingliu
相关文章推荐
- LeetCode 37 Count and Say
- leetcode-Count and Say
- Leetcode--Count and Say
- Leetcode NO.38 Count and Say
- 【LeetCode】Count and Say
- leetcode笔记--Count and Say
- Leetcode:Count and Say
- 【LeetCode38】【Count and Say】StringBuilder
- leetcode解题方案--038--count and say
- 【LeetCode】Count and Say 解题报告
- LeetCode Count and Say
- LeetCode 之 Count and Say
- LeetCode 038 Count and Say
- Leetcode || Count and Say
- leetcode ——Count and Say
- LeetCode刷题笔录Count and Say
- LeetCode - Count and Say
- LeetCode: Count and Say
- [leetcode]Count and Say (伯爵说 C语言实现)
- LeetCode 38 Count and Say