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

本文最后更新于:2025年1月23日 下午

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

题目描述

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

示例 1:

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

示例 2:

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

提示:

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

题解

模拟+排序(超出时间限制)

每次获取子串再将模板串与子串排序比较

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution(object):
def findAnagrams(self, s, p):
"""
:type s: str
:type p: str
:rtype: List[int]
"""
def isSame(str1, str2):
if sorted(str1) == sorted(str2):
return True
else:
return False

s_len, p_len = len(s), len(p)
if s_len < p_len:
return []

i, j = 0, p_len
ans = []

while j <= s_len:
str1 = s[i:j]
if isSame(str1, p):
ans.append(i)
i += 1
j += 1
return ans

滑动窗口

在移动子串时进行删除前一个字符,加入后一个字符操作,节约时空消耗

时间复杂度O(n)空间复杂度O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution(object):
def findAnagrams(self, s, p):
"""
:type s: str
:type p: str
:rtype: List[int]
"""
s_len, p_len = len(s), len(p)
if s_len < p_len:
return []

ans = []

s_count = [0]*26
p_count = [0]*26
for i in range(p_len):
s_count[ord(s[i]) - ord('a')] += 1
p_count[ord(p[i]) - ord('a')] += 1

if s_count == p_count:
ans.append(0)
# 去除第一个元素,加上后一个元素(滑动窗口)
for i in range(s_len-p_len):
s_count[ord(s[i]) - ord('a')] -= 1
s_count[ord(s[i+p_len]) - ord('a')] += 1

if s_count == p_count:
ans.append(i+1)
return ans


LeetCode-438找到字符串中所有字母异位词
https://furthur509.github.io/2025/01/17/LeetCode-438找到字符串中所有字母异位词/
作者
Yang Mingxin
发布于
2025年1月17日
许可协议