1、题目
2、代码
from re import findall
from typing import re
class Solution:
def countAndSay(self, n: int) -> str:
# 1和2是特殊情况
if n == 1:
return "1"
if n == 2:
return "11"
res = [1 ,1]
# 开始计算第N项的值
for i in range(3, n+1):
new_res = [] # 最终生成的列表
num = 1 # 元素出现的次数
cur = res[0] # 指针的值
# 比较当前字符与上一个字符
for s in res[1:]:
if s == cur:
num += 1
else:
new_res.append(num)
new_res.append(cur)
# 重置元素和元素次数
num = 1
cur = s
# 因为最后一个值没有放入结果中,最后增加一次
new_res.append(num)
new_res.append(cur)
res = new_res # 给res重新赋值,下一个循环基于新的res开始
return ''.join(list(map(str, res)))
# # 内置函数
# return haystack.find(needle)
# 单次循环
# 在haystack中截取len(needle)长度的内容,放到列表中
# a = [haystack[x : x+len(needle)-1] for x in haystack if x == needle[0]]
# b = {x: haystack[x:x+len(needle)-1] for x in range(len(haystack)) if haystack[x] == needle[0]}
# for key, value in b.items():
# if needle == value:
# return key
# return -1
class TestSolution:
def test_one(self):
b = Solution()
b.countAndSay(n=5)
#
# def test_two(self):
# b = Solution()
# b.myAtoi(" -23")
#
# def test_three(self):
# b = Solution()
# b.myAtoi("4193 with words")
#
# def test_four(self):
# b = Solution()
# b.myAtoi(" -+987")
class Solution:
def countAndSay(self, n: int) -> str:
prev = "1"
for i in range(n-1):
curr = ""
pos = 0
start = 0
while pos < len(prev):
while pos < len(prev) and prev[pos] == prev[start]:
pos += 1
curr += str(pos - start) + prev[start]
start = pos
prev = curr
return prev