LeetCode 题解工作台

找到字符串中所有字母异位词

给定两个字符串 s 和 p ,找到 s 中所有 p 的 异位词 的子串,返回这些子串的起始索引。不考虑答案输出的顺序。 示例 1: 输入: s = "cbaebabacd", p = "abc" 输出: [0,6] 解释: 起始索引等于 0 的子串是 "cba", 它是 "abc" 的异位词。 起始…

category

3

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

中等 · 滑动窗口(状态滚动更新)

bolt

答案摘要

我们不妨设字符串 的长度为 ,字符串 的长度为 。 如果 $m \lt n$,那么 中不可能存在任何一个子串同 为异位词,返回空列表即可。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 滑动窗口(状态滚动更新) 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定两个字符串 s 和 p,找到 s 中所有 p 的 异位词 的子串,返回这些子串的起始索引。不考虑答案输出的顺序。

 

示例 1:

输入: s = "cbaebabacd", p = "abc"
输出: [0,6]
解释:
起始索引等于 0 的子串是 "cba", 它是 "abc" 的异位词。
起始索引等于 6 的子串是 "bac", 它是 "abc" 的异位词。

 示例 2:

输入: s = "abab", p = "ab"
输出: [0,1,2]
解释:
起始索引等于 0 的子串是 "ab", 它是 "ab" 的异位词。
起始索引等于 1 的子串是 "ba", 它是 "ab" 的异位词。
起始索引等于 2 的子串是 "ab", 它是 "ab" 的异位词。

 

提示:

  • 1 <= s.length, p.length <= 3 * 104
  • s 和 p 仅包含小写字母
lightbulb

解题思路

方法一:滑动窗口

我们不妨设字符串 ss 的长度为 mm,字符串 pp 的长度为 nn

如果 m<nm \lt n,那么 ss 中不可能存在任何一个子串同 pp 为异位词,返回空列表即可。

mnm \ge n 时,我们可以使用一个固定长度为 nn 的滑动窗口来维护 ss 的子串。为了判断子串是否为 pp 的异位词,我们可以用一个固定长度为 2626 的数组 cnt1cnt1 记录 pp 中每个字母的出现次数,再用另一个数组 cnt2cnt2 记录当前滑动窗口中每个字母的出现次数,如果这两个数组相同,那么当前滑动窗口的子串就是 pp 的异位词,我们记录下起始位置。

时间复杂度 O(m×C)O(m \times C),空间复杂度 O(C)O(C)。其中 mm 是字符串 ss 的长度;而 CC 是字符集大小,在本题中字符集为所有小写字母,所以 C=26C = 26

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
    def findAnagrams(self, s: str, p: str) -> List[int]:
        m, n = len(s), len(p)
        ans = []
        if m < n:
            return ans
        cnt1 = Counter(p)
        cnt2 = Counter(s[: n - 1])
        for i in range(n - 1, m):
            cnt2[s[i]] += 1
            if cnt1 == cnt2:
                ans.append(i - n + 1)
            cnt2[s[i - n + 1]] -= 1
        return ans
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    The candidate should demonstrate understanding of sliding window technique and hash table usage.

  • question_mark

    Look for correct handling of window updates and frequency comparison.

  • question_mark

    The candidate should be able to explain the time and space complexity effectively.

warning

常见陷阱

外企场景
  • error

    Incorrectly resizing the window, leading to missed or false positives for anagrams.

  • error

    Not updating the hash table correctly when characters enter and exit the window.

  • error

    Failing to recognize the importance of tracking frequencies in constant time to achieve linear time complexity.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    What if the input strings contain uppercase letters as well? Adapt the hash table to handle both cases.

  • arrow_right_alt

    How would you handle edge cases where s is shorter than p?

  • arrow_right_alt

    Can the solution be optimized further for a scenario with a large number of unique characters?

help

常见问题

外企场景

找到字符串中所有字母异位词题解:滑动窗口(状态滚动更新) | LeetCode #438 中等