Leetcode 438. 找到字符串中所有字母异位词

在这里插入图片描述

心路历程:

看到这个类型的题总以为要用动态规划去做,结果想了半天递推关系没想出来。
看来决定一道题是否适合动态规划不能只按照这道题长得像不像要用动态规划的标准,而应该看重叠子问题现象是否明显。

这道题本质在考察计数集合的用法,可以用sort,也可以用Counter,实测发现Counter的时间复杂度低一点

注意的点:

1、Counter的对象可以直接用==进行比较,且比sort要快速一些。
2、数组的长度 = 数组end索引 - 数组start索引 + 1,简记为数组长度等于索引差加一,方便下次能快速分析边界条件而不用犹豫。

解法:遍历

class Solution:
    def findAnagrams(self, s: str, p: str) -> List[int]:
        from collections import Counter
        # pset = sorted(p)
        pset = Counter(p)
        l = len(p)
        res = []
        for i in range(len(s) - l + 1):
            c = Counter(s[i:i+l])
            if c == pset:  # Counter的计数对象是可以直接比较的
            # if sorted(s[i:i+l]) == pset:
                res.append(i)
        return res

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-09 13:58:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-09 13:58:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-04-09 13:58:02       82 阅读
  4. Python语言-面向对象

    2024-04-09 13:58:02       91 阅读

热门阅读

  1. 面试题:React的真实DOM和虚拟DOM的区别

    2024-04-09 13:58:02       36 阅读
  2. 从零开始构建网络爬虫:ScrapeKit库详解

    2024-04-09 13:58:02       38 阅读
  3. Vue 3中toRaw和markRaw的使用

    2024-04-09 13:58:02       32 阅读
  4. 目录模板-深度学习pytorch实战

    2024-04-09 13:58:02       32 阅读
  5. Ubuntu 16.04版本上安装make 3.8.1

    2024-04-09 13:58:02       40 阅读
  6. CentOS 7中常用的网络与用户相关命令详解

    2024-04-09 13:58:02       32 阅读
  7. 【Python小游戏】扫雷

    2024-04-09 13:58:02       34 阅读
  8. 【LeetCode】热题100:LRU缓存

    2024-04-09 13:58:02       29 阅读
  9. make[2]: texi2dvi: Command not found

    2024-04-09 13:58:02       31 阅读
  10. 5.117 BCC工具之xfsdist.py解读

    2024-04-09 13:58:02       34 阅读
  11. 第 9 场 小白入门赛 -- 蓝桥杯

    2024-04-09 13:58:02       34 阅读
  12. 关于前端资源文件打包问题

    2024-04-09 13:58:02       36 阅读