[leetcode-python3] 38. Count and Say

1957 ワード

38. Count and Say - python3


The count-and-say sequence is a sequence of digit strings defined by the recursive formula:
countAndSay(1) = "1"
countAndSay(n) is the way you would "say"the digit string from countAndSay(n-1), which is then converted into a different digit string.
To determine how you "say"a digit string, split it into the minimal number of groups so that each group is a contiguous section all of the same character. Then for each group, say the number of characters, then say the character. To convert the saying into a digit string, replace the counts with a number and concatenate every saying.
For example, the saying and conversion for digit string "3322251":

Given a positive integer n, return the nth term of the count-and-say sequence.

My Answer 1: (Runtime: 48 ms / Memory Usage: 14.2 MB)

class Solution:
    def countAndSay(self, n: int) -> str:
        if n == 1:
            return "1"
        
        result = "1"
        for i in range(1, n):
            result = self.func(result)
        
        return result
        
    def func(self, s: str) -> str:
        s += '#'
        result = ""
        count = 1
        
        for i in range(1, len(s)):
            if s[i-1] == s[i]:
                count += 1
            else:
                result += str(count) + str(s[i-1])
                count = 1
        
        return result
とても難しい問題です...

ヨガが嫌いなのは私の2倍以上なので、私と同じ同志がたくさんいるようです~^^
しかし、本当に答えを見れば、理解がよくなります.
countAndSay(1)=1のため、結果値は1に初期化されます.
nのように、繰り返し複文を書いて複文を行います...
耳の先端に#を付けるのは、比較的簡単ですが、分かりません.
いずれにしても、ここで繰り返して同じ数字ならcount++で個数を計算します.
異なる場合はresultにcountと数字を加えます.