[String]038 Count and Say*

2018-10-21  本文已影响0人  野生小熊猫

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 where 1 ≤ n ≤ 30, 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"

代码:

方法:

class Solution:
    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """
        i=1
        res="1"
        while(i<n):
            count=0
            ch=res[0]
            new_res=""
            for j in range(len(res)+1):
                if j!=len(res) and res[j]==ch:
                    count+=1
                else:
                    #总结
                    new_res+=str(count)+str(ch)
                    #如果没完就继续
                    if j!=len(res):
                        count=1
                        ch=res[j]
            res=new_res
            i+=1
        
        return res

讨论:

1.这道题在facebook面试中比较常考,而且就一段时间常考,在其他的面试中没咋出现过
2.我咋觉得这道题最重要的是考察你看没看懂题目了(因为我就没看懂= =)
3.这里的j在的range是len(res)+1,因为要留最后一下总结,可千万别忘了,这很重要

Facebook常考
上一篇 下一篇

猜你喜欢

热点阅读