38. Count and Say

本文介绍了一种特殊的数列生成方法——计数并说序列,并提供了两种不同的实现方案。该序列从数字1开始,后续每一项都是对其前一项的描述。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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, 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"

Seen this question in a real interview before?    
Yes
 

分析:读了半天题,最后吐了一口老血。
就是开头给一个数字1,然后我们根据这个规律:前面说字符串中数字的个数,后面写对应的数字
例如:
1
第一次:一个1   ---->11
第二次 :两个1 ------>21
第三次: 一个二一个一  -->1211
第四次:一个1一个2两个1 ----->111221..............就是这样
这道题最开始想到的就是队列,满足先进先出。正好满足这种形式。所以,使用队列解题的代码如下:
class Solution {
public:
    string countAndSay(int n) {
        queue<int> q;
		if(n==0)
			return 0;
		q.push(1);
		if(n==1)
			return "1";
		for(int i=2;i<=n;i++)
		{
			int size=q.size();
			int t=q.front();
			int cnt=0;
			for(int j=0;j<size;j++)
			{
				if(j<size && q.front()==t)
					cnt++;
				if(j==size || (q.front()!=t))
				{
					q.push(cnt);
					q.push(t);
					t=q.front();
					cnt=1;  //因为刚开始肯定相等,所以初始cnt设为0,但是后来我们新取一个t值,但是接着就会pop,所以这里cnt设置为1
				}
				if(j<size)
					q.pop();    //出队列
			}
		}
		string res="";
		while(!q.empty())
		{
			res+=to_string(q.front());
			q.pop();
		}
		return res;
    }
};
当然,我们可以不用队列进行求解,方法二:
class Solution {
public:
    string countAndSay(int n) {
        string s="1";
		for(int i=1;i<=n;i++)
		{
			int count=1;
			string temp="";
			for(int j=1;j<s.length();j++)
			{
				if(s[j]==s[j-1])
					count++;
				else
				{
					temp=temp+(char)(count+'0')+s[j-1];
					count=1;
				}
			}
			s=temp+(char)(count+'0')+s[s.size()-1];
		}
		return s;
    }
};








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值