forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
stamping-the-sequence.py
47 lines (42 loc) · 1.28 KB
/
stamping-the-sequence.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
# Time: O((n - m) * m)
# Space: O((n - m) * m)
import collections
class Solution(object):
def movesToStamp(self, stamp, target):
M, N = len(stamp), len(target)
q = collections.deque()
lookup = [False]*N
result = []
A = []
for i in xrange(N-M+1):
made, todo = set(), set()
for j, c in enumerate(stamp):
if c == target[i+j]:
made.add(i+j)
else:
todo.add(i+j)
A.append((made, todo))
if todo:
continue
result.append(i)
for m in made:
if lookup[m]:
continue
q.append(m)
lookup[m] = True
while q:
i = q.popleft()
for j in xrange(max(0, i-M+1), min(N-M, i)+1):
made, todo = A[j]
if i not in todo:
continue
todo.discard(i)
if todo:
continue
result.append(j)
for m in made:
if lookup[m]:
continue
q.append(m)
lookup[m] = True
return result[::-1] if all(lookup) else []