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
相关推荐
Morwit18 分钟前
【力扣hot100】 85. 最大矩形
c++·算法·leetcode·职场和发展
艾醒26 分钟前
MiniMax M2.5:从黑马到全球顶流的"前世今生"与趣闻
算法
m0_5281744539 分钟前
C++中的代理模式变体
开发语言·c++·算法
2401_883035461 小时前
C++代码风格检查工具
开发语言·c++·算法
啊哦呃咦唔鱼1 小时前
LeetCode hot100-438 找到字符串中所以字母异位词
算法·leetcode·职场和发展
重生之后端学习1 小时前
136. 只出现一次的数字
开发语言·算法·leetcode·职场和发展·深度优先
luckycoding1 小时前
LCR 014.字符串的排列
leetcode
smj2302_796826521 小时前
解决leetcode第3869题.统计区间内奇妙数的数目
python·算法·leetcode
TracyCoder1232 小时前
LeetCode Hot100(66/100)——118. 杨辉三角
算法·leetcode·职场和发展
葳_人生_蕤2 小时前
Leetcode HOT 100
算法·leetcode·职场和发展