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
相关推荐
做怪小疯子2 小时前
LeetCode 热题 100——矩阵——旋转图像
算法·leetcode·矩阵
努力学习的小廉2 小时前
我爱学算法之—— BFS之最短路径问题
算法·宽度优先
高山上有一只小老虎2 小时前
构造A+B
java·算法
木头左2 小时前
缺失值插补策略比较线性回归vs.相邻填充在LSTM输入层的性能差异分析
算法·线性回归·lstm
sin_hielo3 小时前
leetcode 2435
数据结构·算法·leetcode
crescent_悦3 小时前
PTA L1-020 帅到没朋友 C++
数据结构·c++·算法
鳄鱼儿3 小时前
密码算法的OID查阅
算法
lxh01134 小时前
螺旋数组题解
前端·算法·js
铭哥的编程日记4 小时前
《斩获字节跳动offer 最详细的面试真题与破解思路》第一期
面试·职场和发展
czlczl200209255 小时前
算法:二叉树的公共祖先
算法