zoukankan      html  css  js  c++  java
  • leetcode-easy-string- 38 Count and Say

    mycode   91.28%

    思路:题意实在太难理解了,尤其是英文又不好,只能参看下别人的资料,理解下规则。终于理解,题意是n=1时输出字符串1;n=2时,数上次字符串中的数值个数,因为上次字符串有1个1,所以输出11;n=3时,由于上次字符是11,有2个1,所以输出21;n=4时,由于上次字符串是21,有1个2和1个1,所以输出1211。依次类推,写个countAndSay(n)函数返回字符串。

    class Solution(object):
        def countAndSay(self, n):
            """
            :type n: int
            :rtype: str
            """
            from collections import Counter
            if n == 1:
                return '1'     
            a = self.countAndSay(n-1)
             
            res , temp , count = '' , a[0] , 1
            for i in range(1,len(a)):
                if a[i] == temp:
                    count += 1
                else:
                    res += str(count) + str(temp)
                    temp = a[i]
                    count = 1
            res += str(count) + str(temp)
            return res
           

    参考

    把递归换成了for循环

    class Solution(object):
        def countAndSay(self, n):
            """
            :type n: int
            :rtype: str
            """        
            x= '1'
            y=''
            prev = '1'
            for i in range(n-1):
                count = 0
                y = ''
                prev = x[0]
                for j in x:
    
                    if prev==j:
                        count+=1
    
                    else:
                        y+=(str(count)+str(prev))
                        prev = j
                        count = 1
    
    
                y+= (str(count)+str(prev))
                print('y: ',y)
                x = y
    
    
            return(x)
  • 相关阅读:
    Redis学习-开始
    MongoDb学习1
    Git删除tag
    简单实现Windows服务 TopShelf
    autofac 注入普通服务和WCF服务
    MVC过滤器之 OnActionExcuted
    jquery的$.extend()、$.fn和$.fn.extend()
    quartz_jobs.xml标准配置
    常用工具类11-上传类
    常用工具类10-上传水印类
  • 原文地址:https://www.cnblogs.com/rosyYY/p/10997024.html
Copyright © 2011-2022 走看看