38. Count and Say 报数

题目链接
tag:

  • Easy;

question:
  The count-and-say sequence is the sequence of integers with the first five terms as following:

Seq Say
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 where 1 ≤ n ≤ 30, 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"

思路:
  这道计数和读法问题第一次遇到,看似挺复杂,其实仔细一看,算法很简单,题目描述的不是很清楚,其实就是第i+1个字符串是第i个字符串的读法,第一字符串为 “1”,比如第四个字符串是1211,它的读法是 1个1、1个2、2个1,因此第五个字符串是111221。第五个字符串的读法是:3个1、2个2、1个1,因此第六个字符串是312211,代码如下:

class Solution {
public:
    string countAndSay(int n) {
        if (n <= 0) return "";
        string res = "1";
        while (--n) {
            string cur = "";
            for (int i=0; i<res.size(); ++i) {
                int cnt = 1;
                while (i+1 < res.size() && res[i] == res[i+1]) {
                    ++cnt;
                    ++i;
                }
                cur += to_string(cnt) + res[i];
            }
            res = cur;
        }
        return res;
    }
};

出于好奇打印出了前12个数字,发现一个很有意思的现象,不管打印到后面多少位,出现的数字只是由1,2和3组成,网上也有人发现了并分析了原因 (http://www.cnblogs.com/TenosDoIt/p/3776356.html),前十二个数字如下:

1
1 1
2 1
1 2 1 1
1 1 1 2 2 1
3 1 2 2 1 1
1 3 1 1 2 2 2 1
1 1 1 3 2 1 3 2 1 1
3 1 1 3 1 2 1 1 1 3 1 2 2 1
1 3 2 1 1 3 1 1 1 2 3 1 1 3 1 1 2 2 1 1
1 1 1 3 1 2 2 1 1 3 3 1 1 2 1 3 2 1 1 3 2 1 2 2 2 1
3 1 1 3 1 1 2 2 2 1 2 3 2 1 1 2 1 1 1 3 1 2 2 1 1 3 1 2 1 1 3 2 1 1

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

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,948评论 0 10
  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,979评论 0 13
  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 14,299评论 0 38
  • 有朋友失意迷茫,对生活几乎失去信心,找我倾心。 我给他沏一杯茶,他一饮而尽。我问:“你感觉出茶的滋味了吗?”...
    大别山中桃花源阅读 233评论 1 1
  • 今天有人问我很奇怪的一个问题、人为什么生下来就会哭; 人为什么会生下来就哭呢! 相传有一条路叫黄泉路, 有...
    小千晨阅读 1,034评论 0 1

友情链接更多精彩内容