其他分享
首页 > 其他分享> > leetcode38. 报数 �

leetcode38. 报数 �

作者:互联网

题目:

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

    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(1 ≤ n ≤ 30),输出报数序列的第 n 项。

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

示例 1:

  输入: 1
  输出: "1"
示例 2:

  输入: 4
  输出: "1211"

来源:力扣(LeetCode)

解答:

leetcode优秀方案(来自力扣答案统计页,没有明确作者是谁,可留言告知):

 1 class Solution:
 2     def countAndSay(self, n: int) -> str:
 3 
 4         if n == 1: return '1'  # 递归出口
 5         s = self.countAndSay(n-1)
 6         res, count = '', 0
 7         for i in range(len(s)):
 8             count += 1
 9             if i == len(s) - 1 or s[i] != s[i+1]:  # 最后一个字符串要提前终止
10                 res += str(count)
11                 res += s[i]
12                 count = 0
13         return res

class Solution:
def countAndSay(self, n: int) -> str:
def recursion(s, n):
if n == 1:
return s
else:
key = s[0]
s_next = ""
count = 0
for i in range(len(s)):
if s[i] == key:
count += 1
else:
s_next += str(count) + key
count = 1
key = s[i]
return recursion(s_next + str(count) + key, n - 1)

return recursion('1', n)
 1 class Solution:
 2     def countAndSay(self, n: int) -> str:
 3         result = '1'
 4         
 5         for loop in range(n-1):
 6             i = 0
 7             temp = ''
 8             while i < len(result):
 9                 cur_count = 1
10                 while i<len(result)-1 and result[i]==result[i+1]:
11                     cur_count += 1
12                     i += 1
13                 temp = temp + str(cur_count) + result[i]
14                 i += 1
15             result = temp
16         return result

个人愚见:

 1 class Solution:
 2     def countAndSay(self, n: int) -> str:
 3         def worker(n):
 4             n = str(n)
 5             i = 0
 6             j = k = 1
 7             temp = []
 8             while i <= len(n) - 1 and j <= len(n):
 9                 if j == len(n):
10                     temp.append((str(k), n[-1]))
11                     return ''.join([j for i in temp for j in i])
12 
13                 if n[i] == n[j]:
14                     j += 1
15                     k += 1
16                 else:
17                     temp.append((str(k), n[i]))
18                     i = j
19                     j = i + 1
20                     k = 1
21 
22             return ''.join([j for i in temp for j in i])
23 
24         _cache = {1: '1'}
25         for i in range(1, n + 1):
26             if i not in _cache:
27                 _cache[i] = worker(_cache[i - 1])
28 
29         return _cache[n]

 

标签:count,return,leetcode38,self,key,str,报数,def
来源: https://www.cnblogs.com/catyuang/p/11134786.html