Skip to content

Commit 7dcdd8c

Browse files
Create substring_with_concatenation_of_all_words.py
1 parent 3e79dda commit 7dcdd8c

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
from collections import Counter, defaultdict
2+
3+
class Solution(object):
4+
def findSubstring(self, s, words):
5+
"""
6+
:type s: str
7+
:type words: List[str]
8+
:rtype: List[int]
9+
"""
10+
wordBag = Counter(words) # count the freq of each word
11+
wordLen, numWords = len(words[0]), len(words)
12+
totalLen, res = wordLen*numWords, []
13+
for i in range(len(s)-totalLen+1): # scan through s
14+
# For each i, determine if s[i:i+totalLen] is valid
15+
seen = defaultdict(int) # reset for each i
16+
for j in range(i, i+totalLen, wordLen):
17+
currWord = s[j:j+wordLen]
18+
if currWord in wordBag:
19+
seen[currWord] += 1
20+
if seen[currWord] > wordBag[currWord]:
21+
break
22+
else: # if not in wordBag
23+
break
24+
if seen == wordBag:
25+
res.append(i) # store result
26+
return res

0 commit comments

Comments
 (0)