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)
  • 相关阅读:
    Hello,world的几种写法!
    浮动与清除浮动
    css中表格的table-layout属性特殊用法
    CSS之照片集效果
    CSS之transition过渡练习
    CSS之过渡简单应用—日落西山
    CSS之立方体绘画步骤
    CSS之立体球体
    transform
    Vue.sync修饰符与this.$emit('update:xxx', newXXX)
  • 原文地址:https://www.cnblogs.com/rosyYY/p/10997024.html
Copyright © 2011-2022 走看看