一.问题描述
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.
Example 1:
Input: 1 Output: "1"
Example 2:
Input: 4 Output: "1211"
二.解决思路
比较简单的一道题,遍历当前的数字字符串,记录当前相同的数字个数,当当前字符与上个字符不同的时候,更新结果,在结果尾+相同个数和上个字符,注意for循环的边界和最后一个字符的处理
更多leetcode算法题解法请关注我的专栏leetcode算法从零到结束或关注我
欢迎大家一起套路一起刷题一起ac
三.源码
class Solution:
def countAndSay(self, n: int) -> str:
if n==1:
return '1'
if n==2:
return '11'
before='11'
after=''
for i in range(2,n):
after=''
samenum=1
for t in range(1,len(before)):
if before[t]==before[t-1]:
samenum+=1
else:
after+=str(samenum)+before[t-1]
samenum=1
after+=str(samenum)+before[len(before)-1]
before=after
return after
博客围绕LeetCode上的计数说序列问题展开。先给出问题描述,要求根据给定整数n(1 ≤ n ≤ 30)生成该序列的第n项。接着阐述解决思路,需遍历数字字符串,记录相同数字个数,处理好循环边界和最后字符。最后给出源码。
293

被折叠的 条评论
为什么被折叠?



