38. Count and Say解题思路

来源:互联网 发布:linux拷贝当前目录 编辑:程序博客网 时间:2024/06/09 18:21
The count-and-say sequence is the sequence of integers with the first five terms as following:1.     12.     113.     214.     12115.     1112211 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.

解题方法

主要采用的是递归的方法实现的,这里的return返回的是tmp的返回值。
这里我大概写一下这个程序的流程。
1.进入函数之后,会在s = countAndSay(n-1)阶段循环到1,即s = 1,这个时候,继续朝下执行,直接执行,str(len(“1”) - 0) + ‘1’ 即为”11”.这个返回值将会返回给countAndSay(2),也就是countAndSay(2)的值为’11’,继续执行,这个时候,i=0, ch = “1”, tmp=”“.
进入循环当中,因为s[j]不存在不等于s[0]的值,所以循环跳出,tmp=str(2-0)+’1’=”21”,所以CountAndSay(3)的值为’21’,继续循环,这个时候,出现了s[0]和s[1]不相等的情况,这个时候进入for,执行for中的语句,tmp=str(1)+’2’=’12’,返回的tmp是’12’,然后跳出for循环,执行tmp+=str(len(s)-i)+ch 即为tmp=’12’+str(2-1)+’1’=’1211’,这个时候对应的countAndSay(4)的值为’1211’.继续进入循环当中,i,ch,tmp=0,’1’,”.这个时候,就进入for循环当中,i= 1,2,3
因为s[1]!=’1’:所以执行tmp=str(1)+’1’=’11’.
i= 2,s[2]!=’2’,执行tmp=’11’+’1’+’2’=’1112’,
同时把i,ch = 2, ‘1’。
i=3,s[3]==1,跳过。执行结果。
tmp=’1112’+str(4-2)+’1’=’111221’,即countAndSay(5)=’111221’

def countAndSay(n):#(5)    if n == 1: return "1"    s = countAndSay(n - 1)    i, ch, tmp = 0, s[0], ''    for j in range(1, len(s)):        if s[j] != ch:            tmp += str(j - i) + ch            i, ch = j, s[j]    tmp += str(len(s) - i) + ch    return tmpprint(countAndSay(4))

关键还在于弄清题意。