代码改变世界

[LeetCode] 38. Count and Say_Easy

2018-08-11 05:13  Johnson_强生仔仔  阅读(176)  评论(0编辑  收藏  举报

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. Constraints
1)n >= 1 edge case n == 1: return '1'

2. Ideas
recursive helper() , helper()是一个能count and say 之前的string

3. Code
class Solution(object):
    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """
        def helper(n, s):
            if n == 1: return s
            pre, i , temp, count = s[0], 0, "", 0
            while i < len(s):
                if s[i] == pre:
                    count += 1   
                else:
                    temp += str(count) + pre
                    count = 1
                    pre = s[i]
                i += 1
                if i == len(s):
                    temp += str(count) +pre
            return helper(n-1, temp)
        ans = ""
        return helper(n, '1')