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

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

1、题目

image-20240227191448423

2、题解

1、滑动窗口

先在字符串s中构造一个p长度的滑动窗口,在滑动过程中固定窗口中字母的数量,当窗口中每种字母的数量与字符串p中每种字母的数量相同时,说明当前窗口为字符串p的字母异位词。

当字符串s的长度小于字符串p的长度时,字符串s中一定不存在p的异位词,此时字符串s中无法构造和字符串p长度相同的窗口,所以该情况需要单独处理。

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
class Solution:
def findAnagrams(self, s: str, p: str) -> 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]) - 97] += 1
p_count[ord(p[i]) - 97] += 1

if s_count == p_count:
ans.append(0)

for i in range(s_len - p_len):
s_count[ord(s[i]) - 97] -= 1
s_count[ord(s[i + p_len]) - 97] += 1

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

return ans

2、优化滑动窗口

该方法在方法一的基础上,将统计滑动窗口和字符串p中每种字母数量转变为统计二者间每种字母数量的差,当差为0时,即二者为字母异位词。

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
31
32
33
34
35
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
s_len, p_len = len(s), len(p)

if s_len < p_len:
return []

ans = []
count = [0] * 26
for i in range(p_len):
count[ord(s[i]) - 97] += 1
count[ord(p[i]) - 97] -= 1

differ = [c != 0 for c in count].count(True)

if differ == 0:
ans.append(0)

for i in range(s_len - p_len):
if count[ord(s[i]) - 97] == 1: # 窗口中字母 s[i] 的数量与字符串 p 中的数量从不同变得相同
differ -= 1
elif count[ord(s[i]) - 97] == 0: # 窗口中字母 s[i] 的数量与字符串 p 中的数量从相同变得不同
differ += 1
count[ord(s[i]) - 97] -= 1

if count[ord(s[i + p_len]) - 97] == -1: # 窗口中字母 s[i+p_len] 的数量与字符串 p 中的数量从不同变得相同
differ -= 1
elif count[ord(s[i + p_len]) - 97] == 0: # 窗口中字母 s[i+p_len] 的数量与字符串 p 中的数量从相同变得不同
differ += 1
count[ord(s[i + p_len]) - 97] += 1

if differ == 0:
ans.append(i + 1)

return ans

找到字符串中所有字母异位词
http://example.com/2024/02/27/异位词/
作者
Z Z
发布于
2024年2月27日
许可协议