题目描述
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"or11.
1 1is read off as"two 1s"or21.
2 1is read off as"one 2, thenone 1"or1211.
Given an integer n, generate the n th sequence.
Note: The sequence of integers will be represented as a string.
题目大意
题意是:
n=1时输出字符串1;
n=2时,数上次字符串中的数值个数,因为上次字符串有1个1,所以输出11;
n=3时,由于上次字符是11,有2个1,所以输出21;
n=4时,由于上次字符串是21,有1个2和1个1,所以输出1211
思路
就每次计算一下pre_out中各个数字的个数,然后储存到新的cur_out中就好了。
代码
#include<iostream>
#include<cstring>
using namespace std;
string help_fun(string pre_out);
string countAndSay(int n)
{
if(n == 0)return "";
string cur_out = "1";
// 输出第n个结果,就是说要计数到第n个
for(int i=1; i<n; i++)
{
// 每次用当前的cur_out计算的下一次的cur_out
cur_out = help_fun(cur_out);
}
return cur_out;
}
string help_fun(string pre_out)
{
string cur_out = "";
// 用前一次的pre_out计数当前的cur_out
for(int i=0; i<pre_out.size(); )
{
char c = pre_out[i]; // 一个新的数字字符
int j = i;
// 是当前数字字符就让j++
while(j<pre_out.size() && pre_out[j]==c)
{
j++;
}
// 计数当前数字字符
cur_out += (char)('0' + (j - i)); // 保存数字字符个数
cur_out += c; // 保存数字字符
i = j; // 更新下标
}
return cur_out;
}
int main()
{
int n;
while(1)
{
cout<<"输入:";
cin>>n;
cout<<"输出:"<<countAndSay(n)<<endl;
}
return 0;
}
运行结果

以上。
网友评论