-
Notifications
You must be signed in to change notification settings - Fork 43
/
find-all-anagrams-in-a-string.py
282 lines (252 loc) · 8.1 KB
/
find-all-anagrams-in-a-string.py
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
"""
438. Find All Anagrams in a String
Medium
Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1:
Input: s = "cbaebabacd", p = "abc"
Output: [0,6]
Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".
Example 2:
Input: s = "abab", p = "ab"
Output: [0,1,2]
Explanation:
The substring with start index = 0 is "ab", which is an anagram of "ab".
The substring with start index = 1 is "ba", which is an anagram of "ab".
The substring with start index = 2 is "ab", which is an anagram of "ab".
Constraints:
1 <= s.length, p.length <= 3 * 104
s and p consist of lowercase English letters.
"""
# V0
# IDEA : SLIDING WINDOW + collections.Counter()
class Solution(object):
def findAnagrams(self, s, p):
ls, lp = len(s), len(p)
cp = collections.Counter(p)
cs = collections.Counter()
ans = []
for i in range(ls):
cs[s[i]] += 1
if i >= lp:
cs[s[i - lp]] -= 1
### BE AWARE OF IT
if cs[s[i - lp]] == 0:
del cs[s[i - lp]]
if cs == cp:
ans.append(i - lp + 1)
return ans
# V0' : DEV : LTE (LIMITED TIME OUT ERROR)
# from collections import Counter
# class Solution(object):
# def findAnagrams(self, s, p):
# answer = []
# m, n = len(s), len(p)
# if m < n:
# return answer
# pCounter = Counter(p)
# sCounter = Counter(s[:n-1])
# for i in range(0, len(s) - len(p)+1):
# tmp = s[i : i+len(p)]
# if Counter(tmp) == pCounter:
# answer.append(i)
# return answer
# V0''
from collections import Counter
class Solution(object):
def findAnagrams(self, s, p):
answer = []
m, n = len(s), len(p)
if m < n:
return answer
pCounter = Counter(p)
sCounter = Counter(s[:n-1])
index = 0
for index in range(n - 1, m):
sCounter[s[index]] += 1
if sCounter == pCounter:
answer.append(index - (n -1))
sCounter[s[index - (n - 1)]] -= 1
if sCounter[s[index - (n - 1)]] == 0: # NOTE : HAVE TO REMOVE "COUNT = 0" CASE IN COUNTER
del sCounter[s[index - (n - 1)]]
return answer
# V1
# IDEA : Sliding Window with HashMap
# https://leetcode.com/problems/find-all-anagrams-in-a-string/solution/
from collections import Counter
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
ns, np = len(s), len(p)
if ns < np:
return []
p_count = Counter(p)
s_count = Counter()
output = []
# sliding window on the string s
for i in range(ns):
# add one more letter
# on the right side of the window
s_count[s[i]] += 1
# remove one letter
# from the left side of the window
if i >= np:
if s_count[s[i - np]] == 1:
del s_count[s[i - np]]
else:
s_count[s[i - np]] -= 1
# compare array in the sliding window
# with the reference array
if p_count == s_count:
output.append(i - np + 1)
return output
# V1'
# IDEA : Sliding Window with Array
# https://leetcode.com/problems/find-all-anagrams-in-a-string/solution/
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
ns, np = len(s), len(p)
if ns < np:
return []
p_count, s_count = [0] * 26, [0] * 26
# build reference array using string p
for ch in p:
p_count[ord(ch) - ord('a')] += 1
output = []
# sliding window on the string s
for i in range(ns):
# add one more letter
# on the right side of the window
s_count[ord(s[i]) - ord('a')] += 1
# remove one letter
# from the left side of the window
if i >= np:
s_count[ord(s[i - np]) - ord('a')] -= 1
# compare array in the sliding window
# with the reference array
if p_count == s_count:
output.append(i - np + 1)
return output
# V1''
# http://bookshadow.com/weblog/2016/10/23/leetcode-find-all-anagrams-in-a-string/
# https://blog.csdn.net/fuxuemingzhu/article/details/79184109
# IDEA : collections.Counter
class Solution(object):
def findAnagrams(self, s, p):
"""
:type s: str
:type p: str
:rtype: List[int]
"""
ls, lp = len(s), len(p)
cp = collections.Counter(p)
cs = collections.Counter()
ans = []
for i in range(ls):
cs[s[i]] += 1
if i >= lp:
cs[s[i - lp]] -= 1
if cs[s[i - lp]] == 0:
del cs[s[i - lp]]
if cs == cp:
ans.append(i - lp + 1)
return ans
# V1'''
# https://blog.csdn.net/fuxuemingzhu/article/details/79184109
# IDEA : collections.Counter
from collections import Counter
class Solution(object):
def findAnagrams(self, s, p):
"""
:type s: str
:type p: str
:rtype: List[int]
"""
answer = []
m, n = len(s), len(p)
if m < n:
return answer
pCounter = Counter(p)
sCounter = Counter(s[:n-1])
index = 0
for index in range(n - 1, m):
sCounter[s[index]] += 1
if sCounter == pCounter:
answer.append(index - n + 1)
sCounter[s[index - n + 1]] -= 1
if sCounter[s[index - n + 1]] == 0: # NOTE : HAVE TO REMOVE "COUNT = 0" CASE IN COUNTER
del sCounter[s[index - n + 1]]
return answer
# V1''''
# https://blog.csdn.net/fuxuemingzhu/article/details/79184109
# IDEA : TWO POINTERS
class Solution(object):
def findAnagrams(self, s, p):
"""
:type s: str
:type p: str
:rtype: List[int]
"""
count = collections.Counter()
M, N = len(s), len(p)
left, right = 0, 0
pcount = collections.Counter(p)
res = []
while right < M:
count[s[right]] += 1
if right - left + 1 == N:
if count == pcount:
res.append(left)
count[s[left]] -= 1
if count[s[left]] == 0:
del count[s[left]]
left += 1
right += 1
return res
# V1''''''
# http://zxi.mytechroad.com/blog/hashtable/leetcode-438-find-all-anagrams-in-a-string/
# C++
# // Author: Huahua
# // Running time: 35 ms
# class Solution {
# public:
# vector<int> findAnagrams(string s, string p) {
# int n = s.length();
# int l = p.length();
# vector<int> ans;
# vector<int> vp(26, 0);
# vector<int> vs(26, 0);
# for (char c : p) ++vp[c - 'a'];
# for (int i = 0; i < n; ++i) {
# if (i >= l) --vs[s[i - l] - 'a'];
# ++vs[s[i] - 'a'];
# if (vs == vp) ans.push_back(i + 1 - l);
# }
# return ans;
# }
# };
# V2
# Time: O(n)
# Space: O(1)
class Solution(object):
def findAnagrams(self, s, p):
"""
:type s: str
:type p: str
:rtype: List[int]
"""
result = []
cnts = [0] * 26
for c in p:
cnts[ord(c) - ord('a')] += 1
left, right = 0, 0
while right < len(s):
cnts[ord(s[right]) - ord('a')] -= 1
while left <= right and cnts[ord(s[right]) - ord('a')] < 0:
cnts[ord(s[left]) - ord('a')] += 1
left += 1
if right - left + 1 == len(p):
result.append(left)
right += 1
return result