leetcode-easy-string- 38 Count and Say
Posted rosyyy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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)
以上是关于leetcode-easy-string- 38 Count and Say的主要内容,如果未能解决你的问题,请参考以下文章
38 windows_38_thread_CriticalSection 线程-临界区
在测试类中膨胀 ViewBinding 时出错:Binary XML file line #38: Binary XML file line #38: Error inflating class &l