38. Count and Say leetcode python 2016 new season
2016-01-21 13:09
597 查看
The count-and-say sequence is the sequence of integers beginning as follows:
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
if n == 1:
return '1'
else:
prev = self.countAndSay(n - 1)
start = 0
res = ''
while start < len(prev):
count = 0
cur = prev[start]
while start < len(prev) and cur == prev[start]:
start += 1
count += 1
res += str(count) + cur
return res
1, 11, 21, 1211, 111221, ...
1is read off as
"one 1"or
11.
11is read off as
"two 1s"or
21.
21is read off as
"one 2, then
one 1"or
1211.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
if n == 1:
return '1'
else:
prev = self.countAndSay(n - 1)
start = 0
res = ''
while start < len(prev):
count = 0
cur = prev[start]
while start < len(prev) and cur == prev[start]:
start += 1
count += 1
res += str(count) + cur
return res
相关文章推荐
- python 字典中的排序
- python中lambda的另类使用
- 升级python之后,yum下载东西时出现File "/usr/bin/yum", line 30
- Python面向对象学习
- Python之模块搜索路径
- 编写高质量代码--改善python程序的建议(六)续
- 编写高质量代码–改善python程序的建议(五)
- 编写高质量代码--改善python程序的建议(四)下
- 编写高质量代码--改善python程序的建议(四)上
- 编写高质量代码–改善python程序的建议(三)
- 编写高质量代码–改善python程序的建议(二)
- 编写高质量代码--改善python程序的建议(一)
- Windows 7安装scrapy教程
- python:浅析python 中__name__ = '__main__' 的作用
- Python 装饰器
- python自带的调试器
- 我要开始学python了
- Python 第六章 错误、调试和测试
- python实现简单爬虫功能
- 解决crontab python执行环境不一致问题