[leetcode] 19. Count and Say

这个还是一开始没读懂题目,题目如下:

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.

这样的规律依次向下,第一个是"1",然后第二个"11"代表一个1,依次递推,然后给一个数,然后返回在这个规律下的第n个数。【我之前看成了返回这种表达方式的n】【泪目】

因为考虑了递归的低效性,所以我打算用迭代来做,噢,对了,顺便说个坑,我在把int转string的时候用到了itoa这个工具函数,然后VS告诉我itoa不是安全函数请使用_itoa,在我改了后又给我弹出error说_itoa也不是安全的了,请使用_itoa_s,当我在VS中调试正常后,结果发现leetcode的OJ不支持_itoa_s。。。。。

所以我就手写了一个itoa,虽然不算太高效,但是还是能用的。这个题目的题解如下:

class Solution {
public:
	string itoa_better(int n)
	{
		string tmp = "";
		while (n != 0)
		{
			tmp += (n % 10 + '0');
			n = n / 10;
		}
		reverse(tmp.begin(), tmp.end());
		return tmp;
	}

	string Say(string n)
	{
		char word[1] = { n[0] };
		int sum = 1;
		string Say = "";
		string Sum = "";

		for (string::iterator i = n.begin() + 1; i != n.end(); i++)
		{
			if (*i != word[0])
			{
				Say += itoa_better(sum) + word[0];
				sum = 0;
				word[0] = *i;
			}
			sum += 1;
		}
		Say += itoa_better(sum) + word[0];

		return Say;
	}

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

		for (int i = 0; i < n - 1; i++)
		{
			tmp = Say(tmp);
		}

		return tmp;
	}
};

转载于:https://www.cnblogs.com/TinyBox/p/4122266.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值