zoukankan      html  css  js  c++  java
  • Leetcode题库——38.报数


    @author: ZZQ
    @software: PyCharm
    @file: countAndSay.py
    @time: 2018/11/9 14:07
    说明:报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下:
    1. 1
    2. 11
    3. 21
    4. 1211
    5. 111221

    示例 1:
    输入: 1
    输出: "1"
    
    示例 2:
    输入: 4
    输出: "1211"
    

    思路: 从1开始,生成对应字符串,统计相邻的相同数字的个数并生成新的字符串,以此类推。

    class Solution():
        def __init__(self):
            pass
    
        def countAndSay(self, n):
            """
            :type n: int
            :rtype: str
            """
            value = ''
            for i in range(1, n+1):
                if i == 1:
                    value = '1'
                else:
                    len_value = len(value)
                    count = 1
                    new_value = ''
                    if len_value == 1:
                        new_value += '1' + value
                    else:
                        for j in range(1, len_value):
                            if value[j-1] != value[j]:
                                new_value += str(count)
                                new_value += value[j-1]
                                count = 1
                            else:
                                count += 1
                        new_value += str(count) + value[len_value-1]
    
                    value = new_value
            return value
    
  • 相关阅读:
    GCD HDU
    Finding Lines UVALive
    Chinese Mahjong UVA
    DNA Evolution CodeForces
    String Reconstruction (并查集)
    Number Cutting Game HDU
    Paint the Wall ZOJ
    Star sky CodeForces
    Haunted Graveyard ZOJ
    GuGuFishtion HDU
  • 原文地址:https://www.cnblogs.com/zzq-123456/p/9965475.html
Copyright © 2011-2022 走看看