题目:
报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下:
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优秀方案(来自力扣答案统计页,没有明确作者是谁,可留言告知):
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 = 013 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 = 110 while i
个人愚见:
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 += 115 k += 116 else:17 temp.append((str(k), n[i]))18 i = j19 j = i + 120 k = 121 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]
leetcode其他优秀思路:
1 class Solution: 2 def countAndSay(self, n: int) -> str: 3 if n==1: 4 return "1" 5 else: 6 import re 7 str1="" 8 pattern=re.compile(r'(\d)\1{0,}') 9 for i in pattern.finditer(self.countAndSay(n-1)):10 str1 += str(len(i.group(0))) + i.group(0)[0]11 return str112 # https://leetcode-cn.com/problems/count-and-say/comments/2777
class Solution: def countAndSay(self, n): import re s = '1' for _ in range(n - 1): s = ''.join(str(len(p[0])) + p[1] for p in re.findall(r'((.)\2*)', s)) return s # https://leetcode-cn.com/problems/count-and-say/comments/2915