forked from rui-yan/LeetCode-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
substring-with-concatenation-of-all-words.py
99 lines (85 loc) · 3.12 KB
/
substring-with-concatenation-of-all-words.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
from __future__ import print_function
# Time: O((m + n) * k), where m is string length, n is dictionary size, k is word length
# Space: O(n * k)
# 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.
#
# For example, given:
# s: "barfoothefoobarman"
# words: ["foo", "bar"]
#
# You should return the indices: [0,9].
# (order does not matter).
# Sliding window solution
import collections
class Solution(object):
def findSubstring(self, s, words):
"""
:type s: str
:type words: List[str]
:rtype: List[int]
"""
result, m, n, k = [], len(s), len(words), len(words[0])
if m < n*k:
return result
lookup = collections.defaultdict(int)
for i in words:
lookup[i] += 1 # Space: O(n * k)
for i in xrange(k): # Time: O(k)
left, count = i, 0
tmp = collections.defaultdict(int)
for j in xrange(i, m-k+1, k): # Time: O(m / k)
s1 = s[j:j+k]; # Time: O(k)
if s1 in lookup:
tmp[s1] += 1
if tmp[s1] <= lookup[s1]:
count += 1
else:
while tmp[s1] > lookup[s1]:
s2 = s[left:left+k]
tmp[s2] -= 1
if tmp[s2] < lookup[s2]:
count -= 1
left += k
if count == n:
result.append(left)
tmp[s[left:left+k]] -= 1
count -= 1
left += k
else:
tmp = collections.defaultdict(int)
count = 0
left = j+k
return result
# Time: O(m * n * k), where m is string length, n is dictionary size, k is word length
# Space: O(n * k)
class Solution2(object):
def findSubstring(self, s, words):
"""
:type s: str
:type words: List[str]
:rtype: List[int]
"""
result, m, n, k = [], len(s), len(words), len(words[0])
if m < n*k:
return result
lookup = collections.defaultdict(int)
for i in words:
lookup[i] += 1 # Space: O(n * k)
for i in xrange(m+1-k*n): # Time: O(m)
cur, j = collections.defaultdict(int), 0
while j < n: # Time: O(n)
word = s[i+j*k:i+j*k+k] # Time: O(k)
if word not in lookup:
break
cur[word] += 1
if cur[word] > lookup[word]:
break
j += 1
if j == n:
result.append(i)
return result
if __name__ == "__main__":
print(Solution().findSubstring("barfoothefoobarman", ["foo", "bar"]))