C++實(shí)現(xiàn)LeetCode(38.計(jì)數(shù)和讀法)
[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)文章希望大家以后多多支持腳本之家!
- C++實(shí)現(xiàn)LeetCode(94.二叉樹(shù)的中序遍歷)
- C++實(shí)現(xiàn)LeetCode(112.二叉樹(shù)的路徑和)
- C++實(shí)現(xiàn)LeetCode(78.子集合)
- C++實(shí)現(xiàn)LeetCode(47.全排列之二)
- C++實(shí)現(xiàn)LeetCode(90.子集合之二)
- C++實(shí)現(xiàn)LeetCode(113.二叉樹(shù)路徑之和之二)
- C++實(shí)現(xiàn)LeetCode(39.組合之和)
- C++實(shí)現(xiàn)LeetCode(51.N皇后問(wèn)題)
- C++實(shí)現(xiàn)LeetCode(77.Combinations 組合項(xiàng))
- C++實(shí)現(xiàn)LeetCode(46.全排列)
- C++實(shí)現(xiàn)LeetCode(43.字符串相乘)
相關(guān)文章
使用C語(yǔ)言實(shí)現(xiàn)字符串左旋和右旋問(wèn)題
這篇文章主要介紹了使用C語(yǔ)言實(shí)現(xiàn)字符串左旋和右旋問(wèn)題,需要的朋友可以參考下2018-07-07基于C語(yǔ)言實(shí)現(xiàn)的貪吃蛇游戲完整實(shí)例代碼
這篇文章主要介紹了基于C語(yǔ)言實(shí)現(xiàn)的貪吃蛇游戲完整實(shí)例代碼,對(duì)于學(xué)習(xí)游戲開(kāi)發(fā)的朋友有一定的借鑒價(jià)值,需要的朋友可以參考下2014-08-08C++數(shù)據(jù)結(jié)構(gòu)之鏈表詳解
這篇文章主要介紹了C++數(shù)據(jù)結(jié)構(gòu)之鏈表的創(chuàng)建的相關(guān)資料,希望通過(guò)本文幫助到大家,讓大家理解掌握這部分內(nèi)容,需要的朋友可以參考下2021-08-08FFmpeg實(shí)現(xiàn)音頻漸響效果參數(shù)值詳解
這篇文章主要為大家介紹了FFmpeg實(shí)現(xiàn)音頻漸響效果參數(shù)值詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-10-10詳解C++中stoi/stol/stoll函數(shù)的用法
這篇文章主要為大家詳細(xì)介紹了C++中stoi、stol、stoll函數(shù)的具體用法,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)校C++有一點(diǎn)的幫助,需要的可以參考一下2023-03-03C++統(tǒng)計(jì)中英文大小寫(xiě)字母、數(shù)字、空格及其他字符個(gè)數(shù)的方法
這篇文章主要介紹了C++統(tǒng)計(jì)中英文大小寫(xiě)字母、數(shù)字、空格及其他字符個(gè)數(shù)的方法,涉及C++字符串的遍歷與簡(jiǎn)單判定技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2016-05-05