Count and Say
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.
解题思路
代码如下:
class Solution {
public:
string countAndSay(int n) {
if (n == 1) return "1";
string pre = "1", next;
for (int i = 1; i < n; ++i) {
int m = 0, n = 0;
while (n < pre.size()) {
while(n + 1 < pre.size() && pre[n] == pre[n+1]) n++;
stringstream ss;
ss << n - m + 1;
next += ss.str() + pre[n];
m = n = n + 1;
}
pre = next;
next = "";
}
return pre;
}
};
本文介绍了一种递归算法来生成CountandSay数列。该数列从1开始,后续每一项都是对前一项的读法进行数字表示。例如1被读作one1即11,11被读作two1s即21等。文章提供了一个C++实现示例。
492

被折叠的 条评论
为什么被折叠?



