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
相关推荐
洛水水11 小时前
【力扣100题】81.寻找两个正序数组的中位数
数据结构·算法·leetcode
happymaker062611 小时前
LeetCodeHot100——155.最小栈
算法
洛水水11 小时前
【力扣100题】85.每日温度
算法·leetcode·职场和发展
Coder-magician11 小时前
《代码随想录》刷题打卡day15:二叉树part05
数据结构·c++·算法
Kurisu_红莉栖11 小时前
力扣56合并区间
算法·leetcode
Irissgwe12 小时前
算法的时间复杂度和空间复杂度
数据结构·c++·算法·c·时间复杂度·空间复杂度
随意起个昵称12 小时前
区间dp-基础题目3(永别)
c++·算法
周末也要写八哥12 小时前
有向图Hierholzer算法的另一种实现
算法
bIo7lyA8v12 小时前
算法调优中的性能回归与基准测试分析的技术8
算法·数据挖掘·回归
有点。12 小时前
C++贪心算法二(练习题)
c++·算法·贪心算法