美文网首页
count-and-say

count-and-say

作者: 穿越那片海 | 来源:发表于2017-03-07 11:08 被阅读0次

Easy

Count-and-say 序列是一个如下的整数序列。 给定一个整数n,返回第n个序列。序列用string表示。

1, 11, 21, 1211, 111221, ...
1读作一个1,或11
11读作两个1,或21
21读作一个2一个1,或1211

Leecode把此题归为easy档,我倒是觉得有些难度。
最开始我把题理解错误,认为是: 第一个数是n,那么由n衍生出的coutn-and-say序列的第n个值是什么?所以就有了下面的code。(开始是string=str(n))。
将问题简化为求上面序列的第n个值,应该有更简单的办法,欢迎反馈。

from itertools import groupby
class Solution(object):
    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """
        if n == 0 or n == 1:
            return str(n)
        string = '1'
        for _ in xrange(n-1):
            keys = [key for key, _ in groupby(string)]
            counts = [len(list(group)) for _, group in groupby(string)]
            resp = ''
            for key, count in zip(keys,counts):
                resp += str(count)+key
            string = resp
        return string

相关文章

网友评论

      本文标题:count-and-say

      本文链接:https://www.haomeiwen.com/subject/jwopgttx.html