leetcode 38. Count and Say
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, 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"
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | class Solution( object ): def countAndSay( self , n): """ :type n: int :rtype: str """ """ 1=>1 """ k = "1" def say(m): # greedy ans = "" c = 1 for i in xrange ( 1 , len (m)): if m[i] = = m[i - 1 ]: c + = 1 else : ans + = str (c) + m[i - 1 ] c = 1 ans + = str (c) + m[ - 1 ] return ans for i in xrange ( 1 , n): k = say(k) return k |
经典的字符计数问题!或者也可以使用贪心算法求解,还可以避免最后为len-1的判断。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | class Solution( object ): def countAndSay( self , n): """ :type n: int :rtype: str """ """ 1=>1 """ k = "1" def say(m): # greedy ans = "" i = 0 while i< len (m): s, c = m[i], 1 while i + 1 < len (m) and m[i + 1 ] = = m[i]: i + = 1 c + = 1 ans + = str (c) + str (s) i + = 1 return ans for i in xrange ( 1 , n): k = say(k) return k |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
2017-06-03 python nltk 入门demo