[LeetCode] Count and Say 计数和读法

简介:

The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 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 sequence.

Note: The sequence of integers will be represented as a string.

这道计数和读法问题还是第一次遇到,看似挺复杂,其实仔细一看,算法很简单,就是对于前一个数,找出相同元素的个数,把个数和该元素存到新的string里。代码如下:

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

参考资料:

https://discuss.leetcode.com/topic/20195/c-solution-easy-understand

本文转自博客园Grandyang的博客,原文链接:[LeetCode] Count and Say 计数和读法

,如需转载请自行联系原博主。

相关文章
|
6月前
【Leetcode -696.计数二进制字串 -697.数组的度】
【Leetcode -696.计数二进制字串 -697.数组的度】
17 0
|
11天前
|
JavaScript
【leetcode】204. 计数质数 暴力 & 埃拉托斯特尼法
【leetcode】204. 计数质数 暴力 & 埃拉托斯特尼法
11 0
|
6月前
【Leetcode -292.Nim游戏 -326. 3的幂 -338.比特位计数】
【Leetcode -292.Nim游戏 -326. 3的幂 -338.比特位计数】
19 0
|
2月前
LeetCode题 338比特位计数,20有效的括号,415字符串相加
LeetCode题 338比特位计数,20有效的括号,415字符串相加
35 0
|
3月前
leetcode-338:比特位计数
leetcode-338:比特位计数
17 0
|
4月前
|
机器学习/深度学习 算法 vr&ar
☆打卡算法☆LeetCode 204. 计数质数 算法解析
☆打卡算法☆LeetCode 204. 计数质数 算法解析
|
9月前
LeetCode-计数质数
LeetCode-计数质数
|
10月前
【leetcode】204. 计数质数
【leetcode】204. 计数质数
力扣刷题记录——326.3的幂、338. 比特位计数、342. 4的幂、350. 两个数组的交集 II
力扣刷题记录——326.3的幂、338. 比特位计数、342. 4的幂、350. 两个数组的交集 II
力扣刷题记录——326.3的幂、338. 比特位计数、342. 4的幂、350. 两个数组的交集 II
LeetCode 357. Count Numbers with Unique Digits
给定一个非负整数 n,计算各位数字都不同的数字 x 的个数,其中 0 ≤ x < 10n 。
61 0
LeetCode 357. Count Numbers with Unique Digits