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)