[leetcode]: 38. Count and Say

阅读: 评论:0

[leetcode]: 38. Count and Say

[leetcode]: 38. Count and Say

1.题目

The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 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, generate the nth sequence.
一个读数的序列1, 11, 21, 1211, 111221,…给定n求这个序列第n个string是什么。
Note: The sequence of integers will be represented as a string.

2.分析

读数的规律:从前往后读
一个数字x如果后面没有相邻的相同数字,则读作 1x
例如 1–》11,21–》12 11
一个数字x如果后面有相邻相同数字,一共有n个,则读作nx
例如 11–》21, 111221(3个1,2个2,1个1)–》312211

找到规律后遍历一遍字符串即可。注意序列从第1个开始,不是从第0个开始。

3.代码

def countAndSay(self, n):if n<1:return elif n==1:return "1"cur="11"next=""for t in range(n-2):i=0while i<len(cur):count=1while i+count<len(cur) and cur[i]==cur[i+count]:count+=1next+=str(count)+cur[i]i+=countcur=nextnext=""return cur

本文发布于:2024-02-04 20:52:25,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170716156159504.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:leetcode   Count
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23