LeetCode 37. Count and Say

Posted jzssuanfa

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 37. Count and Say相关的知识,希望对你有一定的参考价值。

n-1为迭代的次数。字符串num初始为"1".

每次迭代就開始数字符串中数字的个数,有一个trick是,当 当前数字与前一位(高位)不同一时候就停止计数:

所以1211的下一个字符串应该是111221(1个1, 1个2, 2个1), 而不是1231(而不是1个2, 3个1).


代码:

class Solution 
{
public:
	string countAndSay(int n) 
	{
		string num("1"), next_num;
		
		for (int i = 1; i < n; ++ i)
		{
			int cnt = ‘0‘, last = num[0];
			next_num.clear();
			for (size_t j = 0; j < num.size(); ++ j)
			{
				if (num[j] == last)
				{
					++ cnt;
				} else
				{
					next_num += cnt;
					next_num += last;
					cnt = ‘1‘;
					last = num[j];
				}
			}
			next_num += cnt;
			next_num += last;
			num = next_num;
		}

		return num;
	}
};





以上是关于LeetCode 37. Count and Say的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode38. Count and Say

Count and Say leetcode

Leetcode 之Count and Say(35)

Leetcode Count and Say

[LeetCode] Count and Say

LeetCode题意分析&解答38. Count and Say