''' The count-and-say sequence is the sequence of integers with the first five terms as following: 1. 1 2. 11 3. 21 4. 1211 5. 111221 1 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 where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence. Note: Each term of the sequence of integers will be represented as a string. ''' class Solution: def countAndSay(self, n: int) -> str: if n==1: return '1' if n==2: return '11' count_num = '11' for i in range(3,n+1): temp_out='' index=0 # print(len(count_num)) while index<len(count_num): c=count_num[index]# 取出当前的字符 temp_num=1# 当前字符计数值为1 # print(c) # 从当前索引index开始一直向后遍历,找到第一个不等于当前字符的数值 for j in range(index+1,len(count_num)): # print(index+1,len(count_num)) if count_num[j]==c: temp_num+=1 index=j # print(temp_num,'temp_num') else: index=j-1 break index+=1 temp_out += str(temp_num) + c # print('here',str(temp_num) ,c) count_num=temp_out # print(i,count_num) return count_num if __name__=='__main__': print(Solution().countAndSay(6))
leetcode 38. Count and Say python
最新推荐文章于 2022-10-18 23:53:32 发布