Count and Say-LeetCode
2014-10-22 15:04
218 查看
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.
用到了一个平时没有用到的stringstream,用来将int转化为string,十分便捷,使用方法见下面的博文链接。
http://www.cppblog.com/Sandywin/archive/2007/07/13/27984.html
代码:
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.
用到了一个平时没有用到的stringstream,用来将int转化为string,十分便捷,使用方法见下面的博文链接。
http://www.cppblog.com/Sandywin/archive/2007/07/13/27984.html
代码:
class Solution { public: string getnextstr(string str) { stringstream ss; char key = str[0]; char current = str[0]; int count = 0; for (int i = 0; i < str.length(); i++) { current = str[i]; if (key == current) { count++; } else { ss<<count<<key; key = current; count = 1; } } ss<<count<<key; return ss.str(); } string countAndSay(int n) { string result = "1"; if ( n <= 0) { return NULL; } if (n == 1) { return result; } for (int i = 0; i < n - 1; i++) { result = getnextstr(result); } return result; } };
相关文章推荐
- LeetCode——Count and Say
- leetcode-38 Count and Say
- leetcode之count and say
- LeetCode-Count and Say
- leetcode由易入难——【6】Count and Say
- LeetCode--Count and Say
- Leetcode|Count and Say
- 【LeetCode】Count and Say
- LeetCode 38 Count and Say(C,C++,Java,Python)
- LeetCode38 Count and Say(C语言解决)
- [leetcode]50 Count and Say
- leetcode Count and Say
- [Leetcode]38--Count and Say
- [LeetCode] Count and Say
- LeetCode38 - Count and Say
- Leetcode: Count and Say
- 【LeetCode】Count and Say
- [LeetCode] Count and Say, Solution
- leetcode 64: Count and Say
- leetcode:Count and Say