5.Leetcode 38:Count and Say 笔记

1:题目描述

Given an integer n, generate the nth term of the count-and-say sequence.

找规律,给定一个数n后,写出第n行的字符串

2:题目分析

突然发现自己的Say实在不发达,看了半个多小时才知道咋回事。n就是再说n-1行的内容:“有‘x1’个‘num1’和‘x2’个‘num2’……”,分析完毕,开始写代码

3:解题思路

 1 class Solution(object):
 2     def countAndSay(self, n):
 3         """
 4         :type n: int
 5         :rtype: str
 6         """
 7         num='1'
 8         temp_nums=''
 9         nums='1'
10         for i in range(1,n): 
11             num=nums[0]
12             j=0
13             count=0                #计数器
14             while j<len(nums):#遍历字符串
15                 if num==nums[j]: #num与当前字符相同,count+1
16                     count+=1
17                 else:
18                     temp_nums+=(str(count)+num) #否则,将count与num接在temp_nums后面
19                     num=nums[j]    #num替换为当前字符
20                     count=1             #从1开始计数
21                 if j==len(nums)-1: #很重要!很重要!很重要!
22                     temp_nums+=(str(count)+num)
23                     nums=temp_nums #得到第n行的字符串
24                     temp_nums=''   #清空临时字符串
25                     break
26                 j+=1
27         if nums=='1': # 以上并不能输出n=1的情况,因为上面是range(1,n)
28             return nums
29         else:  
30             return nums

4:解题感悟

①标注’很重要‘的部分,给我一个能够妥善处理字符串最后一个字符的办法(这可是我绞尽脑仁两个小时后的产物啊ε=(´ο`*))))

②这个题交给python处理的确很方便,但自己确实不大会say,多锻炼锻炼吧 ヾ(◍°∇°◍)ノ゙



原文地址:https://www.cnblogs.com/19991201xiao/p/8407141.html