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
相关推荐
孤飞6 小时前
zero2Agent:面向大厂面试的 Agent 工程教程,从概念到生产的完整学习路线
算法
zjeweler7 小时前
“网安+护网”终极300多问题面试笔记-3共3-综合题型(最多)
笔记·网络安全·面试·职场和发展·护网行动
技术专家7 小时前
Stable Diffusion系列的详细讨论 / Detailed Discussion of the Stable Diffusion Series
人工智能·python·算法·推荐算法·1024程序员节
Hacker_Nightrain7 小时前
详解Selenium 和Playwright两大框架的不同之处
自动化测试·软件测试·selenium·测试工具·职场和发展
csdn_aspnet7 小时前
C# (QuickSort using Random Pivoting)使用随机枢轴的快速排序
数据结构·算法·c#·排序算法
鹿角片ljp7 小时前
最长回文子串(LeetCode 5)详解
算法·leetcode·职场和发展
paeamecium9 小时前
【PAT甲级真题】- Cars on Campus (30)
数据结构·c++·算法·pat考试·pat
chh56310 小时前
C++--模版初阶
c语言·开发语言·c++·学习·算法
RTC老炮10 小时前
带宽估计算法(gcc++)架构设计及优化
网络·算法·webrtc
dsyyyyy110110 小时前
计数孤岛(DFS和BFS解决)
算法·深度优先·宽度优先