惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

雷峰网
雷峰网
GbyAI
GbyAI
Stack Overflow Blog
Stack Overflow Blog
Apple Machine Learning Research
Apple Machine Learning Research
The Cloudflare Blog
WordPress大学
WordPress大学
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
F
Fortinet All Blogs
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Microsoft Azure Blog
Microsoft Azure Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 聂微东
L
LangChain Blog
云风的 BLOG
云风的 BLOG
Jina AI
Jina AI
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
I
InfoQ
大猫的无限游戏
大猫的无限游戏
MyScale Blog
MyScale Blog
人人都是产品经理
人人都是产品经理
小众软件
小众软件
量子位
The GitHub Blog
The GitHub Blog
博客园 - 【当耐特】

博客园 - Dabay

[Leetcode][Python]56: Merge Intervals [Leetcode][Python]55: Jump Game [Leetcode][Python]54: Spiral Matrix [Leetcode][Python]53: Maximum Subarray [Leetcode][Python]52: N-Queens II [Leetcode][Python]51: N-Queens [Leetcode][Python]50: Pow(x, n) [Leetcode][Python]49: Anagrams [Leetcode][Python]48: Rotate Image [Leetcode][Python]47: Permutations II [Leetcode][Python]46: Permutations [Leetcode][Python]45: Jump Game II [Leetcode][Python]44:Wildcard Matching [Leetcode][Python]43: Multiply Strings [Leetcode][Python]42: Trapping Rain Water [Leetcode][Python]41: First Missing Positive [Leetcode][Python]40: Combination Sum II [Leetcode][Python]39: Combination Sum [Leetcode][Python]37: Sudoku Solver
[Leetcode][Python]19: Remove Nth Node From End of List
Dabay · 2015-02-06 · via 博客园 - Dabay
# -*- coding: utf8 -*-
'''
__author__ = 'dabay.wang@gmail.com'

38: Count and Say
https://oj.leetcode.com/problems/count-and-say/

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.
Note: The sequence of integers will be represented as a string.

===Comments by Dabay===
题意半天没搞懂。原来是给的数字n是几,就返回第几个字符串。例如,如果n是5,就返回“111221”这个字符串。
第一个铁定是1,然后用say的方式来往后生成下一个字符串。

say的时候:
比较下一个数字是否一样,
如果一样,计数器加一
如果不一样,say
'''

class Solution:
# @return a string
def countAndSay(self, n):
current_result = "1"
start = 1
while start < n:
previous_result = current_result
current_result = ""
counting_number = None
counter = 0
for num in previous_result:
if counting_number is None:
counting_number = num
counter = 1
elif counting_number == num:
counter += 1
else:
current_result += "%s%s" % (counter, counting_number)
counting_number = num
counter = 1
else:
current_result += "%s%s" % (counter, counting_number)
start += 1
return current_result

def main():
sol = Solution()
print sol.countAndSay(5)

if __name__ == "__main__":
import time
start = time.clock()
main()
print "%s sec" % (time.clock() - start)