-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0030-substring-with-concatenation-of-all-words.py
More file actions
47 lines (40 loc) · 1.56 KB
/
0030-substring-with-concatenation-of-all-words.py
File metadata and controls
47 lines (40 loc) · 1.56 KB
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
# time complexity: O(a + n*b)
# space complexity: O(a + b)
from collections import Counter, defaultdict
from typing import List
class Solution:
def findSubstring(self, s: str, words: List[str]) -> List[int]:
result = []
sSize = len(s)
wordLen = len(words[0])
wordCount = Counter(words)
def slidingWindow(left):
foundCount = defaultdict(lambda: 0)
totalMatched = 0
for right in range(left, len(s), wordLen):
if right + wordLen > sSize:
break
newWord = s[right: right + wordLen]
if newWord not in wordCount:
foundCount = defaultdict(lambda: 0)
totalMatched = 0
left = right + wordLen
else:
foundCount[newWord] += 1
if foundCount[newWord] > wordCount[newWord]:
while foundCount[newWord] > wordCount[newWord]:
leftMost = s[left: left + wordLen]
foundCount[leftMost] -= 1
left += wordLen
if leftMost != newWord:
totalMatched -= 1
else:
totalMatched += 1
if totalMatched == len(words):
result.append(left)
for i in range(wordLen):
slidingWindow(i)
return result
s = "barfoothefoobarman"
words = ["foo", "bar"]
print(Solution().findSubstring(s, words))