python-leetcode-找到字符串中所有字母异位词

438. 找到字符串中所有字母异位词 - 力扣(LeetCode)

python 复制代码
from collections import Counter
class Solution:
    def findAnagrams(self, s: str, p: str) -> List[int]:
        if len(s) < len(p):  
            return []  # s 比 p 还短,直接返回空列表

        res = []
        p_count = Counter(p)  # 统计 p 中字符出现次数
        s_count = Counter(s[:len(p)])  # 统计窗口内的字符出现次数

        if s_count == p_count:
            res.append(0)  # 第一个窗口匹配

        for i in range(len(p), len(s)):
            s_count[s[i]] += 1  # 加入新的字符
            s_count[s[i - len(p)]] -= 1  # 移除窗口左侧字符

            if s_count[s[i - len(p)]] == 0:  
                del s_count[s[i - len(p)]]  # 清理计数为 0 的字符

            if s_count == p_count:
                res.append(i - len(p) + 1)  # 记录起始索引

        return res
相关推荐
rannn_1111 分钟前
【力扣hot100】二叉树专题+总结
java·算法·leetcode·二叉树
啊嘞嘞?4 分钟前
力扣(岛屿数量)
算法·leetcode
zander25822 分钟前
LeetCode 198. 打家劫舍
算法·leetcode·深度优先
吃着火锅x唱着歌29 分钟前
LeetCode 648.单词替换
算法·leetcode·职场和发展
一只积极向上的小咸鱼1 小时前
分词器tokenizer
算法·llm
Elsa️7461 小时前
leetcode 14.最长公共前缀
算法·leetcode·职场和发展
不会代码的小猴1 小时前
6. Qt网络编程
开发语言·c++·笔记·qt·算法
Zguigo1 小时前
树的前序|中序|后序遍历【使用栈实现】
数据结构·算法
zhanghaha13141 小时前
HTML系列教程:4_什么是 HTML 元素(零基础超详细讲解)
前端·算法·html
TAN-90°-1 小时前
Deep Learning for Computer Vision——Training CNNs and CNN Architectures
人工智能·深度学习·神经网络·算法·机器学习·计算机视觉·cnn