[leetcode]38. Count and Say

38. Count and Say

Easy

6804923FavoriteShare

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 where 1 ≤ n ≤ 30, 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"

 

这题我一开始看了半天没看懂。。后面才理解

第一个输入是1,输出是1,这个不解释了

第二个输出就是在念第一个的输出,第一个输出是1,也就是1个1,所以输出11

第三个输出同理,11是2个1,所以是21,

第四个输出同理,21是由1个2和1个1组成,所以是1211

如此类推。。

 

本题理解了意思后就很好解决了,因为他题目说了n<=30,所以嘛。。。按顺序迭代下去就OK了

就是很直观的数出来就行。。。

例如

1211

我们就按顺序搞就行,一开始,只有1个1,于是就是11,只有1个2,于是是12,然后2个1,组合就说111221了。。

所以很直观的就是计算出连续序列的长度就行。。

 

代码如下

string countAndSay(int n) 
{
	string answer = "1";

	int i = 1;
	int counter = 1;

	int j1 = 0;

	while (i < n) {
		string temp_string = "";
		
		for (int j = 0; j < answer.size(); j++) {
			int temp = answer[j] - 49;

			j1 = j + 1;
			while (j1 < answer.size() && answer[j] == answer[j1]) {
				j = j1;
				j1++;
				counter++;
				
			}

			string t = to_string(counter);
			temp_string.append(t);
			temp_string.append(1,answer[j]);
			counter = 1;
		}

		answer = temp_string;
		i++;
	}

	return answer;
}

顺便装个B,竟然用时超过了100%的c++代码。。。不过用的空间确实比较大,懒得改了先这样吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值