亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

C++實(shí)現(xiàn)LeetCode(38.計(jì)數(shù)和讀法)

 更新時(shí)間:2021年07月14日 17:10:38   作者:Grandyang  
這篇文章主要介紹了C++實(shí)現(xiàn)LeetCode(38.計(jì)數(shù)和讀法),本篇文章通過(guò)簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下

[LeetCode] 38. Count and Say 計(jì)數(shù)和讀法

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

這道計(jì)數(shù)和讀法問(wèn)題還是第一次遇到,看似挺復(fù)雜,其實(shí)仔細(xì)一看,算法很簡(jiǎn)單,就是對(duì)于前一個(gè)數(shù),找出相同元素的個(gè)數(shù),把個(gè)數(shù)和該元素存到新的 string 里。代碼如下:

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 個(gè)數(shù)字,發(fā)現(xiàn)一個(gè)很有意思的現(xiàn)象,不管打印到后面多少位,出現(xiàn)的數(shù)字只是由 1, 2 和3 組成,前十二個(gè)數(shù)字如下:

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

到此這篇關(guān)于C++實(shí)現(xiàn)LeetCode(38.計(jì)數(shù)和讀法)的文章就介紹到這了,更多相關(guān)C++實(shí)現(xiàn)計(jì)數(shù)和讀法內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論