码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_38题——Count and Say(string,迭代计数)

时间:2015-04-20 11:10:37      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:

Count and Say

 Total Accepted: 39135 Total Submissions: 154215My Submissions

 

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.

 

Show Tags
Have you met this question in a real interview? 
Yes
 
No
 

Discuss

开始没理解这道题的意思,他是说求这个序列的第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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!