LeetCode 题解工作台
找到字符串中所有字母异位词
给定两个字符串 s 和 p ,找到 s 中所有 p 的 异位词 的子串,返回这些子串的起始索引。不考虑答案输出的顺序。 示例 1: 输入: s = "cbaebabacd", p = "abc" 输出: [0,6] 解释: 起始索引等于 0 的子串是 "cba", 它是 "abc" 的异位词。 起始…
3
题型
7
代码语言
3
相关题
当前训练重点
中等 · 滑动窗口(状态滚动更新)
答案摘要
我们不妨设字符串 的长度为 ,字符串 的长度为 。 如果 $m \lt n$,那么 中不可能存在任何一个子串同 为异位词,返回空列表即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 滑动窗口(状态滚动更新) 题型思路
题目描述
给定两个字符串 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 * 104s和p仅包含小写字母
解题思路
方法一:滑动窗口
我们不妨设字符串 的长度为 ,字符串 的长度为 。
如果 ,那么 中不可能存在任何一个子串同 为异位词,返回空列表即可。
当 时,我们可以使用一个固定长度为 的滑动窗口来维护 的子串。为了判断子串是否为 的异位词,我们可以用一个固定长度为 的数组 记录 中每个字母的出现次数,再用另一个数组 记录当前滑动窗口中每个字母的出现次数,如果这两个数组相同,那么当前滑动窗口的子串就是 的异位词,我们记录下起始位置。
时间复杂度 ,空间复杂度 。其中 是字符串 的长度;而 是字符集大小,在本题中字符集为所有小写字母,所以 。
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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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?