标签:
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.
开始没理解这道题的意思,他是说求这个序列的第n个数是什么
#include<iostream>
#include<string>
#include<vector>
using namespace std;
//这道题采用迭代计数的方法,假设已知前面一个数,然后根据这个数计算出下面一个数
string the_next_number(string vec)
{
string temp_last;
string temp;
temp.push_back(vec[0]);
if(vec.size()>1)
{
int i=1;
while(i!=vec.size())
{
if(vec[i]==vec[i-1])
{
temp.push_back(vec[i]);
i++;
}
else
{
temp_last.push_back(temp.size()+48);
temp_last.push_back(vec[i-1]);
temp.clear();
temp.push_back(vec[i]);
i++;
}
}
}
if(temp.size()!=0)
{
temp_last.push_back(temp.size()+48);
temp_last.push_back(temp[0]);
}
return temp_last;
}
string countAndSay(int n) {
string str_result="1";
if(n==1)
return str_result;
else
n=n-1;
while(n--)
{
str_result=the_next_number(str_result);
}
return str_result;
}
int main()
{
cout<<countAndSay(1)<<endl;
cout<<countAndSay(2)<<endl;
cout<<countAndSay(3)<<endl;
cout<<countAndSay(4)<<endl;
system("pause");
return 1;
}
leetcode_38题——Count and Say(string,迭代计数)
标签:
原文地址:http://www.cnblogs.com/yanliang12138/p/4440752.html