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
相关推荐
西柚研究生1234563 小时前
论文分析17:YOLOv11_UAVNet:无人机航拍图像专用目标检测算法
人工智能·python·深度学习·算法·目标检测
hetao17338374 小时前
2026-09-17 hetao1733837 的刷题记录
c++·算法
午彦琳4 小时前
2026.9.17
数据结构·算法·leetcode
木井巳5 小时前
【记忆化搜索】不同路径
java·算法·leetcode·深度优先·剪枝·推荐算法
怕浪猫6 小时前
从 Windows 换到 Mac 三个月,我真香了
算法·面试·架构
aichitang20247 小时前
前端小skill
前端·人工智能·算法·ai·前端框架
All for pursuit.8 小时前
【链表-9】146.LRU缓存
数据结构·c++·算法·leetcode
木子算法8 小时前
测出来的值会抖:约束和目标带噪声时,「可行」和「更好」该怎么判
人工智能·算法·目标跟踪
圣保罗的大教堂8 小时前
leetcode 1477. 找两个和为目标值且不重叠的子数组 中等
leetcode
hanlin039 小时前
刷题笔记:力扣第144题-二叉树的前序遍历
笔记·算法·leetcode