一.问题描述
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.
二.我的解题思路
问题比较简单,挨个生成第2…n-1个序列即可。每个序列的生成都需要遍历前一个字符串序列。测试通过的程序如下:
class Solution {
public:
string countAndSay(int n) {
vector<string> res_vec;
res_vec.push_back("1"); char tmp1,tmp2;
if(n==0) return "";
if(n==1) return res_vec[0];
for (int i = 1; i<n; i++){
string tmp_idx("");
int curr = 0; int end = res_vec[i - 1].length(); int pri = 0; string str = res_vec[i - 1];
while (curr + 1<end){
if (str[curr + 1] == str[curr]){
curr++;
}
else{
int tmp_len = curr - pri + 1;
tmp1 = '0' + tmp_len;
tmp2 = str[pri];
tmp_idx = tmp_idx + tmp1 + tmp2;
curr++;
pri = curr;
}
}
if (curr == pri)
{
tmp1 = '0' + 1;
tmp2 = str[pri];
tmp_idx = tmp_idx + tmp1 + tmp2;
}
else{
int tmp_len = curr - pri + 1;
tmp1 = '0' + tmp_len;
tmp2 = str[pri];
tmp_idx = tmp_idx + tmp1 + tmp2;
curr++;
pri = curr;
}
res_vec.push_back(tmp_idx);
}
return res_vec[n-1];
}
};

本文介绍了一种生成计数并说序列的方法。该序列从1开始,后续每一项都是对前一项的描述。例如,1被描述为“one1”,即11;11被描述为“two1s”,即21。文中提供了一个C++实现方案,通过迭代生成序列。
170

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



