Skip to content

Commit d8061d4

Browse files
committed
2020-05-05 438. Find All Anagrams in a String
1 parent 9658ef6 commit d8061d4

1 file changed

Lines changed: 71 additions & 0 deletions

File tree

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
# -*- coding: utf-8 -*-
2+
# @Author: 何睿
3+
# @Create Date: 2020-05-05 15:29:17
4+
# @Last Modified by: 何睿
5+
# @Last Modified time: 2020-05-05 20:08:00
6+
7+
from typing import List
8+
from copy import deepcopy
9+
from collections import defaultdict
10+
11+
12+
class Solution:
13+
def findAnagrams(self, s: str, p: str) -> List[int]:
14+
15+
if not s or not p:
16+
return []
17+
18+
p_dict = defaultdict(int)
19+
tmp_dict = defaultdict(int)
20+
for char in p:
21+
p_dict[char] += 1
22+
23+
for char in s[:len(p)]:
24+
tmp_dict[char] += 1
25+
26+
res = []
27+
28+
for i in range(0, len(s) - len(p)):
29+
if tmp_dict == p_dict:
30+
res.append(i)
31+
32+
tmp_dict[s[i]] -= 1
33+
if tmp_dict[s[i]] == 0:
34+
tmp_dict.pop(s[i])
35+
tmp_dict[s[i + len(p)]] += 1
36+
37+
if tmp_dict == p_dict:
38+
res.append(len(s) - len(p))
39+
return res
40+
41+
def findAnagrams2(self, s: str, p: str) -> List[int]:
42+
43+
if not s or not p:
44+
return []
45+
46+
p_dict = defaultdict(int)
47+
for char in p:
48+
p_dict[char] += 1
49+
50+
left, right, cnt = 0, 0, len(p)
51+
res = []
52+
53+
while right < len(s):
54+
p_dict[s[right]] -= 1
55+
56+
if p_dict[s[right]] >= 0:
57+
cnt -= 1
58+
if cnt == 0:
59+
res.append(left)
60+
if right - left + 1 == len(p):
61+
if p_dict[s[left]] >= 0:
62+
cnt += 1
63+
p_dict[s[left]] += 1
64+
left += 1
65+
66+
right += 1
67+
68+
return res
69+
70+
71+

0 commit comments

Comments
 (0)