【leetcode c++】38 Count and Say

Count and Say

The count-and-say sequence is the sequenceof 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 one1" or 1211.

Given an integer n, generate the nthsequence.

Note: The sequence of integers will berepresented as a string.

 

这道题首先要读懂,首先,读法都能理解了,一串数字,从左到右数数字。21读成1个2、1个1,然后数字表示成1211。长一点的比如111221读成3个1、2个2、1个1。数字表示312211。然后,这些数字怎么来呢?1, 11, 21, 1211,111221, ...

首先规定,第一个是1;第二个数字就是第一个的读法;第三个数字就是第二个数字的读法;第四个数字就是第三个数字的读法……

是不是要一发递归?→ →

 

瞄了一眼函数头。stringcountAndSay(int n)。输入是int,输出是string。看来不打算给我们递归了。当然也可以重新写一个新函数,然后调用。

 

这里就不递归了。我们用个中间值string来传递好了。

其实我解题本质就是,用循环来实现递归而已。没递归漂亮。

 

Leetcode的AcceptedSolutions Runtime Distribution(15-06-10)

 

源码:(VS2013)

 

#include <iostream>
#include <sstream>
#include <map>
#include <vector>

using namespace std;

string countAndSay(int n);
int main(){

	cout << countAndSay(5);

	return 0;
}

string countAndSay(int n){
	if (1 == n)
	{
		return "1";
	}
	string s;//intתstring
	stringstream ss;

	string tempString = "";
	char tempChar;
	string tempRes = "1";
	int myCount = 0;
	for (int i = 2; i <= n;i++)
	{
		tempString = tempRes;
		tempRes = "";
		string::iterator iter = tempString.begin();
		tempChar = *iter;
		while (iter != tempString.end())
		{
			if (tempChar == *iter)
			{
				myCount++;
			}
			else
			{
				ss << myCount;
				ss >> s;//intתstring
				tempRes += s;
				tempRes += tempChar;
				ss.clear();
				//21
				tempChar = *iter;
				myCount = 1;
			}
			iter++;
		}
		ss << myCount;
		ss >> s;//intתstring
		tempRes += s;
		iter--;
		tempRes += *iter;
		ss.clear();

		myCount = 0;
	}

	return tempRes;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值