LeetCode--038--报数(*)

问题描述:

报数序列是指一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下:

1.     1
2.     11
3.     21
4.     1211
5.     111221

1 被读作  "one 1"  ("一个一") , 即 11
11 被读作 "two 1s" ("两个一"), 即 21
21 被读作 "one 2",  "one 1" ("一个二" ,  "一个一") , 即 1211

给定一个正整数 n ,输出报数序列的第 n 项。

注意:整数顺序将表示为一个字符串。

方法1:

 1 class Solution(object):
 2     def countAndSay(self, n):
 3         """
 4         :type n: int
 5         :rtype: str
 6         """
 7         ans = "1"
 8         n -= 1
 9         while n > 0:
10             res = ""
11             pre = ans[0]
12             count = 1
13             for i in range(1, len(ans)):
14                 if pre == ans[i]:
15                     count += 1
16                 else:
17                     res += str(count) + pre
18                     pre = ans[i]
19                     count = 1
20             res += str(count) + pre
21             ans = res
22             n -= 1
23         return ans
24         

变体:

 1 class Solution(object):
 2     def countAndSay(self, n):
 3         """
 4         :type n: int
 5         :rtype: str
 6         """
 7         ans = '1'
 8         while n > 1:
 9             ans = self.countStr(ans)
10             n -= 1
11         return ans
12     
13     def countStr(self,s):
14         count = 0;ans = "";tmp = s[0]
15         for i in range(len(s)):
16             if s[i] == tmp:
17                 count += 1
18             else:
19                 ans += str(count) + tmp
20                 tmp = s[i];count = 1
21         ans += str(count) + tmp
22         return ans

方法2:递归

 1 class Solution(object):
 2     def countAndSay(self, n):
 3         """
 4         :type n: int
 5         :rtype: str
 6         """
 7         if n == 1:
 8             return '1'
 9         s = self.countAndSay(n-1)
10         res = ''
11         count = 0
12         for i in range(len(s)):
13             count += 1
14             if i == len(s) - 1 or s[i] != s[i+1]:
15                 res += str(count)
16                 res += s[i]
17                 count = 0
18         return res
19         

2018-07-23 21:30:30

 

posted @ 2018-07-23 21:31  Assange  阅读(247)  评论(0编辑  收藏  举报