Leetcodes Solution 38 Count and Say

匯總

雪之下雪乃:leetcode解題總匯?

zhuanlan.zhihu.com圖標

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

1. 12. 113. 214. 12115. 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: 1Output: "1"

Example 2:

Input: 4Output: "1211"

思路1

直接根據輸入的n對數列數n次

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 count = 1; while((i + 1 < res.size()) && (res[i] == res[i+1])){ count++; i++; } cur += to_string(count) + res[i]; } res = cur; } return res; }};

推薦閱讀:

九章演算法 | Google面試題:原子計數
027 Remove Element[E]
面試不再怕,20行Python代碼幫你搞懂LRU演算法
精選 TOP45 值得學習的Python項目
期望為線性時間的選擇演算法

TAG:演算法 | 數據結構 | 編程 |