题目:
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) {
string str = "1";
if(n == 1)
return str;
n = n - 1;
while(n--)
{
string tmp = "";
int len = str.length();
int cnt = 1;
char s = str[0];
for(int i = 1;i < len; ++i)
{
if(s == str[i])
cnt++;
else
{
tmp += ('0' + cnt);
tmp += s;
s = str[i];
cnt = 1;
}
}
tmp += ('0' + cnt);
tmp += s;
str = tmp;
}
return str;
}
};
本文介绍了一种生成计数并说序列的方法,通过遍历字符串实现从初始值1开始生成序列,每一步都根据前一步的结果生成新的序列。文章提供了一个C++实现示例。
493

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



