leetcode - 438. Find All Anagrams in a String

Description

Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Example 1:

复制代码
Input: s = "cbaebabacd", p = "abc"
Output: [0,6]
Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".

Example 2:

复制代码
Input: s = "abab", p = "ab"
Output: [0,1,2]
Explanation:
The substring with start index = 0 is "ab", which is an anagram of "ab".
The substring with start index = 1 is "ba", which is an anagram of "ab".
The substring with start index = 2 is "ab", which is an anagram of "ab".

Constraints:

复制代码
1 <= s.length, p.length <= 3 * 10^4
s and p consist of lowercase English letters.

Solution

Sliding window, use a hash table to keep track of all the characters we have already visited. If all the characters are visited, then we get our answer.

Time complexity: o ( n ) o(n) o(n)

Space complexity: o ( n ) o(n) o(n)

Code

python3 复制代码
class Solution:
    def findAnagrams(self, s: str, p: str) -> List[int]:
        available_chars = {}
        for c in p:
            available_chars[c] = available_chars.get(c, 0) + 1
        distinct_chars = len(available_chars)
        left = -1
        res = []
        cur_chars = available_chars.copy()
        for right in range(len(s)):
            if s[right] not in available_chars:
                left = right
                cur_chars = available_chars.copy()
            else:
                while cur_chars[s[right]] <= 0:
                    left += 1
                    cur_chars[s[left]] += 1
                cur_chars[s[right]] -= 1
            if list(cur_chars.values()) == [0] * distinct_chars:
                res.append(left + 1)
        return res

Other method sliding window

python3 复制代码
class Solution:
    def findAnagrams(self, s: str, p: str) -> List[int]:
        p_chars = {}
        for c in p:
            p_chars[c] = p_chars.get(c, 0) + 1
        s_chars = {}
        left = -1
        res = []
        for right in range(len(s)):
            s_chars[s[right]] = s_chars.get(s[right], 0) + 1
            while len(s_chars) > len(p_chars) or s_chars.get(s[right], 0) > p_chars.get(s[right], 0):
                left += 1
                s_chars[s[left]] -= 1
                if s_chars[s[left]] == 0:
                    s_chars.pop(s[left])
            if s_chars == p_chars:
                res.append(left + 1)
        return res
相关推荐
阿Y加油吧20 分钟前
两道位运算 / 摩尔投票经典题复盘:只出现一次的数字 & 多数元素
数据结构·算法·leetcode
Evand J26 分钟前
【课题推荐】三模型IMM交互式多模型滤波算法,匀速/左转/右转目标跟踪,附MATLAB代码测试结果
算法·matlab·目标跟踪·无人机·imm·多模型
05候补工程师1 小时前
【408狂飙·数据结构】核心考点深度复盘:数组地址计算、特殊矩阵压缩存储与树的五大性质解题直觉
数据结构·笔记·线性代数·考研·算法·矩阵
青山师1 小时前
HashMap深度解析:哈希冲突、扩容机制与线程安全
算法·安全·哈希算法·java面试·hashmap源码
货拉拉技术1 小时前
私域转化率翻倍的秘密:我们把多模态Agent融进了私域营销
人工智能·算法·设计模式
WL_Aurora1 小时前
备战蓝桥杯国赛【Day 17】
算法·蓝桥杯
kcuwu.1 小时前
决策树与集成学习深度解析:从原理到实践
算法·决策树·集成学习
programhelp_2 小时前
2026 Fall Coinbase Software Engineer OA 真题分享与通关指南
算法
CQU_JIAKE2 小时前
5.19【A】
算法
数智工坊2 小时前
【FDA论文阅读】: 傅里叶域自适应——零训练成本的语义分割无监督域适配方法
论文阅读·人工智能·学习·算法·自动驾驶