LeetCode 38. 外觀數列 Count and Say

Table of Contents

一、中文版

二、英文版

三、My answer

四、解題報告


一、中文版

給定一個正整數 n(1 ≤ n ≤ 30),輸出外觀數列的第 n 項。

注意:整數序列中的每一項將表示爲一個字符串。

「外觀數列」是一個整數序列,從數字 1 開始,序列中的每一項都是對前一項的描述。前五項如下:

1.     1
2.     11
3.     21
4.     1211
5.     111221
第一項是數字 1

描述前一項,這個數是 1 即 “一個 1 ”,記作 11

描述前一項,這個數是 11 即 “兩個 1 ” ,記作 21

描述前一項,這個數是 21 即 “一個 2 一個 1 ” ,記作 1211

描述前一項,這個數是 1211 即 “一個 1 一個 2 兩個 1 ” ,記作 111221

 

示例 1:

輸入: 1
輸出: "1"
解釋:這是一個基本樣例。
示例 2:

輸入: 4
輸出: "1211"
解釋:當 n = 3 時,序列是 "21",其中我們有 "2" 和 "1" 兩組,"2" 可以讀作 "12",也就是出現頻次 = 1 而 值 = 2;類似 "1" 可以讀作 "11"。所以答案是 "12" 和 "11" 組合在一起,也就是 "1211"。

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/count-and-say
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

二、英文版

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. You can do so recursively, in other words from the previous member read off the digits, counting the number of digits in groups of the same digit.

Note: Each term of the sequence of integers will be represented as a string.

 

Example 1:

Input: 1
Output: "1"
Explanation: This is the base case.
Example 2:

Input: 4
Output: "1211"
Explanation: For n = 3 the term was "21" in which we have two groups "2" and "1", "2" can be read as "12" which means frequency = 1 and value = 2, the same way "1" is read as "11", so the answer is the concatenation of "12" and "11" which is "1211".

 

三、My answer

class Solution:
    def countAndSay(self, n: int) -> str:
        nums = ['','1']
        if n == 1:
            return '1'
        for i in range(2, n+1):
            p = []
            s = ''
            for x in nums[i-1]:
                if p == [] or x == p[0]:
                    p.append(x)
                else:
                    s += str(len(p))
                    s += p[0]
                    p = []
                    p.append(x)
                    
            s += str(len(p))
            s += p[0]
            nums.append(s)
        
        return nums[-1]

四、解題報告

數據結構:數組

算法:遍歷

實現:遍歷 2 到 n 之間的每一箇中間結果,存入 nums 中,這樣題目要求的結果就是 nums[-1]。

nums 中先存入初始值,也就是第一個 n = 1 的結果。

數組 p 用來存每一次相同元素,這樣 p 的長度就是裏面元素出現的個數。

如果 p 爲空或者字符 x 與第一個 p[0] 值相同,說明從開始到該字母 x 一直沒變,則把 x 存入 p 中。

當字母 x 與 數組 p 中元素不一樣時,說明字符變化,則需要把數據 p 中現有元素及個數存入字符串 s 中。最後 s 再放入 nums 數組中。注意 s 和 p 的重新清零的位置。 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章