!!!!? 从1(第一步)开始产生后面的数据。 

38. 报数

每次for循环需要保存这一次的结果为下一次计算作铺垫 。


1 读 one one

11 不读 one one one one,读 two one, 连着一起相同的数会先说数量再说值。

以上是基础。接下来看怎么得到下一项的结果。从题目所给出的示例4 : 1211 到 5 : 111221。1211 第一位是1,所以读作 one one,也就是 1 1 。2读作one two, 所以是12。 11连着读作two one, 所以是21。这所有加起来就是答案 111221。

思路:根据报数的特点,我们可以根据上一项的结果推导下一项。我们遍历上一项,辅以计数变量统计一下某些数字出现的次数。同时我们要不断保存上一项。


           由上一层推下一层:例

           第四层推第五层:第四层为1211,从左至右读作:一个一,一个二,两个一   

                                                                         故写作==>11 12 21

           不难看出规律:

                                1.使用计数器计数初始值为1,上层每一个数,不相同记为1

                                2.如果相邻两值相等则计数器加一,记为2。如11下层记为两个一(21),22下层记为两个                                        二(22),而不是211和222.  

           然后遍历保存拼接。
 


class Solution(object):
    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """
        s = '1'
        for _ in range(1, n):
            nextS = ''
            countC = 1
            for i in range(1, len(s)+1):
                if i == len(s) or s[i] != s[i-1]:
                    nextS += str(countC) + s[i-1]
                    countC = 1
                else:
                    countC +=1
            s = nextS
        return s

转:https://blog.csdn.net/AntiZheng/article/details/82763409 

一样的思路:

class Solution(object):
    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """
        if n == 1:
            return "1"
        prev = "1"
        res = ""
        for i in range(1, n):
            count = 1
            for j in range(len(prev)-1):
                if prev[j] == prev[j+1]:
                    count += 1
                else:
                    res += str(count)+prev[j]
                    count = 1
            res += str(count)+prev[-1]
            prev = res
            res = ""
        return prev

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-07-01
  • 2022-01-04
  • 2022-12-23
  • 2022-02-19
  • 2021-10-13
  • 2021-08-26
猜你喜欢
  • 2021-07-27
  • 2021-09-11
  • 2021-04-05
  • 2022-01-03
  • 2021-07-27
  • 2022-12-23
相关资源
相似解决方案