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
相关推荐
米粒17 小时前
力扣算法刷题 Day 27
算法·leetcode·职场和发展
Fuxiao___8 小时前
C 语言核心知识点讲义(循环 + 函数篇)
算法·c#
Mr_Xuhhh8 小时前
LeetCode hot 100(C++版本)(上)
c++·leetcode·哈希算法
漫随流水8 小时前
c++编程:反转字符串(leetcode344)
数据结构·c++·算法
穿条秋裤到处跑10 小时前
每日一道leetcode(2026.03.31):字典序最小的生成字符串
算法·leetcode
CoovallyAIHub12 小时前
VisionClaw:智能眼镜 + Gemini + Agent,看一眼就能帮你搜、帮你发、帮你做
算法·架构·github
CoovallyAIHub12 小时前
低空安全刚需!西工大UAV-DETR反无人机小目标检测,参数减少40%,mAP50:95提升6.6个百分点
算法·架构·github
CoovallyAIHub12 小时前
IEEE Sensors | 湖南大学提出KGP-YOLO:先定位风电叶片再检测缺陷,三数据集mAP均超87%
算法
Yupureki12 小时前
《算法竞赛从入门到国奖》算法基础:动态规划-路径dp
数据结构·c++·算法·动态规划
副露のmagic13 小时前
数组章节 leetcode 思路&实现
算法·leetcode·职场和发展