初级算法_字符串 --- 外观数列【人麻了,这个题暂时放弃】

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿_焦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值