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

被折叠的 条评论
为什么被折叠?



