• LeetCode Easy: 38. 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, generate the nth term of the count-and-say sequence.

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

    二、解题思路

    题目的意思就是:“计数”和“说数”,后一个就是前一个的表达,如果1211,就是:1个1,1个2,两个1,写出来就是111221。给定字符串是 s,相邻的相等的子串进行计数,结果为 str(count)+str[ i ]

    三、代码

    #coding:utf-8
    def countStr(strs):
        counts = 0
        s = ""
        i = 0
    
        while i in range(len(strs)):  #遍历字符串
            for j in range(i,len(strs)):    #遍历当前字符之后的字符
                if strs[j] != strs[i]:      
                    counts = j - i
                    s = s + str(counts) + strs[i]
                    break
                if j == len(strs)-1:     # 到最后一个字符时,应该单独考虑,因为python中的range范围包左不包右
                    counts = j -i + 1
                    s = s + str(counts) + strs[i]
            i = i+counts
        print(s)
        return s
    
    def countAndSay(n):
        """
        :type n: int
        :rtype: str
        """
        if n == 1:
            print(1)
            return 1
        s = '1'
        while n > 1:
            s = countStr(s)
            n -= 1
        return s
    
    if __name__ == '__main__':
        countAndSay(10)

    四、“别人”代码

    http://www.cnblogs.com/chruny/p/4926290.html

    class Solution(object):
        def countStr(self,s):
            count = 0;ans = "";tmp = s[0]
            for i in range(len(s)):
                if s[i] == tmp:
                    count += 1
                else:
                    ans += str(count) + tmp
                    tmp = s[i];count = 1
            ans += str(count) + tmp
            return ans
        def countAndSay(self, n):
            """
            :type n: int
            :rtype: str
            """
            ans = '1'
            while n > 1:
                ans = self.countStr(ans)
                n -= 1
            return ans
    
    既然无论如何时间都会过去,为什么不选择做些有意义的事情呢
  • 相关阅读:
    windows2000/xp运行命令全集
    IP数据包的校验和算法C#版(原)
    做系统清理的批处理
    Combox用ValueMember 之后再添加一项
    安装部署基础——Windows Application
    文件编码
    Left/right join 和inner join 区别
    应用Url重写时CSS引用问题
    数据绑定控件单选框
    算法题:水杯倒水的问题
  • 原文地址:https://www.cnblogs.com/xiaodongsuibi/p/8643222.html
Copyright © 2020-2023  润新知