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.
I dont actually agree this is an easy one.... I made mistakes anyway....
#include <string>
#include <vector>
#include <iostream>
using namespace std;
string nextString(string tmp) {
string nextString = "";
for(int i = 0; i < tmp.size(); ++i) {
int count = 1;
while(i + 1 < tmp.size() && tmp[i] == tmp[i+1]) {
i++;
count++;
}
nextString += to_string(count) + tmp[i];
}
return nextString;
}
string countAndSay(int n) {
string tmp = "1";
for(int i = 1; i < n; ++i) {
tmp = nextString(tmp);
}
return tmp;
}
int main(void) {
cout << countAndSay(3) << endl;
}
// Second Version
string nextStringII(string tmp) {
string res = "";
int count = 1;
for(int i = 1; i < tmp.size(); ++i) {
if(tmp[i] == tmp[i-1]) {
count++;
} else {
res += to_string(count) + tmp[i-1];
count = 1;
}
}
int n = tmp.size();
if(count > 1) return res += to_string(count) + tmp[n - 1];
return res += to_string(count) + tmp[n-1];
}

本文介绍了一种生成计数读数序列的算法实现,通过迭代方式生成序列中的每一项。该序列从1开始,后续每一项都是对其前一项的描述。例如,1被描述为“one 1”即11;11被描述为“two 1s”即21等。文章提供了两种不同的C++实现方法。
637

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



