Leetcode 38.报数 By Python

It reported that the number sequence is a sequence of integers, for an integer number of packets in the order in which to obtain the next number. Front five as follows:

1.     1
2.     11
3.     21
4.     1211
5.     111221

1 is read as "One 1" ( "a a"), i.e., 11.
11 is read as "two 1s" ( "two one"), i.e., 21.
21 is read as "one 2", "one 1 " ( " a two", "a a"), i.e., 1211.

Given a positive integer n (. 1 ≤ n ≤ 30), reported that the number of the output sequence of n items.

Note: The order of integer represented as a string.

Example 1:

输入: 1
输出: "1"

Example 2:

输入: 4
输出: "1211"

Thinking

  • The number of reported during manual simulation, like a gradual recurrence
  • A very wonderful solution is to use itertoolsthe groupbymethod, will automatically help us to complete the process of counting, distance usage is as follows:
[k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B
[list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D

Code

from itertools import groupby
class Solution:
    def countAndSay(self, n: int) -> str:
        prev = '1'
        
        for i in range(1,n):    # 计算n-1次
            cnt = 0
            tmp = ''
            pos_char = prev[0]
            length = len(prev)
            for j in range(length):    # 数数的过程
                if prev[j] != pos_char:
                    tmp += str(cnt) + pos_char
                    cnt = 1
                    pos_char = prev[j]
                else:
                    cnt += 1
            tmp += str(cnt) + pos_char
            prev = tmp       # 完成一次更新
        return prev
    
    
# 利用了itertools的解法
from itertools import groupby
class Solution:
    def countAndSay(self, n: int) -> str:
        prev = '1'
        for i in range(1,n):
            prev = ''.join([str(len(list(g))) + k for k,g in groupby(prev)])
        return prev

Stated

Source: stay button (LeetCode)
link: https://leetcode-cn.com/problems/count-and-say

Guess you like

Origin www.cnblogs.com/MartinLwx/p/11521416.html