[LeetCode] Count and Say

1.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"

2.题目要求:求一个数组的第n项,而这个数组的通项公式可以理解成:
第1项:1
第2项:11
第3项:21
第4项:1211
第5项:111221
第6项:312211
...
第n项:第n-1项的数字串从左到右读出来,比如说第2项是11,因为第1项是1,读起来就是1个1,所以第2项的11前一个1表示后一个1的计数,以此类推。

3.方法:设计一个函数可以求出某数字串的下一个数字串,只要调用该函数n-1次就能得到我们想要的结果。

4.代码:
class Solution {
private:
string Count(string s)
{
string r;
int i=0;
int c;
while (i < s.size())
{
c = 1;
char t;
if (s[i] == s[i + 1])
{
while (s[i] == s[i + 1])
{
c++;
i++;
}
t = c + '0';
r = r + t + s[i];
i++;
}
else
{
t = '1';
r = r + t + s[i];
i++;
}
}
return r;
}
public:
string countAndSay(int n) {
if (n == 1)
return "1";
string s = "1";
while (--n)
{
s = Count(s);
}
return s;
}
};

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容