-
Notifications
You must be signed in to change notification settings - Fork 612
/
30.py
64 lines (52 loc) · 1.56 KB
/
30.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
'''
You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.
Example 1:
Input:
s = "barfoothefoobarman",
words = ["foo","bar"]
Output: [0,9]
Explanation: Substrings starting at index 0 and 9 are "barfoor" and "foobar" respectively.
The output order does not matter, returning [9,0] is fine too.
Example 2:
Input:
s = "wordgoodstudentgoodword",
words = ["word","student"]
Output: []
'''
class Solution(object):
def findSubstring(self, s, words):
"""
:type s: str
:type words: List[str]
:rtype: List[int]
"""
if not str or not words:
return []
counts = {}
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
result = []
n, numOfWords, fixLen = len(s), len(words),len(words[0])
for index in range(0, n-numOfWords*fixLen+1):
seen = {}
index_j = 0
while index_j < numOfWords:
word = s[index + index_j*fixLen: index + (index_j+1)*fixLen]
if word in counts:
if word in seen:
seen[word] += 1
else:
seen[word] = 1
if seen[word] > counts[word]:
break
else:
break
index_j += 1
if index_j == numOfWords:
result.append(index)
return
# Time: O(N^2)
# Space: O(N)