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
相关推荐
自我意识的多元宇宙3 分钟前
数据结构----插入排序
数据结构·算法·排序算法
im_AMBER3 分钟前
Leetcode 162 除了自身以外数组的乘积 | 接雨水
开发语言·javascript·数据结构·算法·leetcode
Westward-sun.5 分钟前
YOLO目标检测算法与mAP评估指标详解(附示例)
算法·yolo·目标检测
cpp_250115 分钟前
P1873 [COCI 2011/2012 #5] EKO / 砍树
数据结构·c++·算法·题解·二分答案·洛谷·csp
啊哦呃咦唔鱼17 分钟前
leetcodehot100-347. 前 K 个高频元素
数据结构·算法·leetcode
玛丽莲茼蒿17 分钟前
Leetcode hot100 多数元素【简单】
算法·leetcode·职场和发展
AbandonForce18 分钟前
Map类:pair键值对|map的基本操作|operator[]
开发语言·c++·算法·leetcode
澈20720 分钟前
C++核心:封装与static静态成员实战指南
开发语言·c++·算法
田梓燊24 分钟前
力扣:146.LRU 缓存
算法·leetcode·缓存
_深海凉_30 分钟前
LeetCode热题100-杨辉三角
算法·leetcode·职场和发展