Skip to content

Commit 417e346

Browse files
authored
Create stamping-the-sequence.py
1 parent 8bd1479 commit 417e346

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

Python/stamping-the-sequence.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Time: O((n - m) * m)
2+
# Space: O((n - m) * m)
3+
4+
import collections
5+
6+
7+
class Solution(object):
8+
def movesToStamp(self, stamp, target):
9+
M, N = len(stamp), len(target)
10+
11+
q = collections.deque()
12+
lookup = [False]*N
13+
result = []
14+
A = []
15+
for i in xrange(N-M+1):
16+
made, todo = set(), set()
17+
for j, c in enumerate(stamp):
18+
if c == target[i+j]:
19+
made.add(i+j)
20+
else:
21+
todo.add(i+j)
22+
A.append((made, todo))
23+
if todo:
24+
continue
25+
result.append(i)
26+
for m in made:
27+
if lookup[m]:
28+
continue
29+
q.append(m)
30+
lookup[m] = True
31+
32+
while q:
33+
i = q.popleft()
34+
for j in xrange(max(0, i-M+1), min(N-M, i)+1):
35+
made, todo = A[j]
36+
if i not in todo:
37+
continue
38+
todo.discard(i)
39+
if todo:
40+
continue
41+
result.append(j)
42+
for m in made:
43+
if lookup[m]:
44+
continue
45+
q.append(m)
46+
lookup[m] = True
47+
return result[::-1] if all(lookup) else []

0 commit comments

Comments
 (0)