题目描述:
The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 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 term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1
Output: "1"
Example 2:
Input: 4 Output: "1211"
要完成的函数:
string countAndSay(int n)
代码:
#include<string>
#include<sstream>
string int2str(int &i)//实现从int到string的转换
{
string s;
stringstream ss(s);
ss << i;
return ss.str();
}
int count(string a,int b,int index)//在a中,从index这个位置开始,有多少个数字为b的,返回这个数量
{
int result=0;
for(int i=index;i<a.size();i++)
{
if(a[i]==b)
result++;
else
break;
}
return result;
}
string countAndSay(int n) //主要函数
{
string result="1";
string result1;
int result2;
if(n==1)
{
return result;
}
while(--n)
{
int i=0;
result1="";
while(i<result.size())
{
result2=count(result,result[i],i);
result1+=int2str(result2);
result1+=result[i];
i+=result2;
}
result=result1;
}
return result;
}
说明:
1、这道题可能有的朋友不太明白题目在讲什么,说一下。
首先,n=1的时候,输出“1”的序列。
n=2的时候,上一个序列中,从第一个数字开始,直到最后一个数字。数一下上一个序列有多少个连续的1,答案是“1”个“1”,所以输出“11”的序列。
n=3的时候,上一个序列中,从第一个数字开始,直到最后一个数字。数一下上一个序列有多少个连续的1,答案是“2”个“1”,所以输出“21”的序列。
n=4的时候,上一个序列中,从第一个数字开始,直到最后一个数字。数一下上一个序列有多少个连续的2,答案是“1”个“2”,所以输出12;数一下上一个序列中有多少个连续的1,答案是“1”个“1”,所以输出11。合起来就是“1211”。
n=5的时候,上一个序列中,从第一个数字开始,直到最后一个数字。数一下上一个序列有多少个连续的1,答案是“1”个“1”,所以输出“11”,数一下上一个序列中有多少个连续的2,答案是“1”个“2”,所以输出“12”,数一下上一个序列中有多少个连续的1,答案是“2”个“1”,所以输出“21”。合起来就是“111221”。
看明白之后,本题采用最暴力的方法去做,定义了三个函数。每个函数的功能都在注释中写了。自己跑一遍应该就看出来了。
2、c++的int2str在c++11中可以to_string(int)输出,比如cout<<to_string(123)+"908"<<endl;可以得到123908的输出。
但在c++11之前,就要使用#include<sstream>中的方法,像本文那样使用就可以了。