Skip to content

Commit 425b2d6

Browse files
authored
Create find-pattern-in-infinite-stream-i.py
1 parent e017ce3 commit 425b2d6

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Time: O(p + n)
2+
# Space: O(p)
3+
4+
class InfiniteStream:
5+
def next(self):
6+
pass
7+
8+
9+
# kmp
10+
class Solution(object):
11+
def findPattern(self, stream, pattern):
12+
"""
13+
:type stream: InfiniteStream
14+
:type pattern: List[int]
15+
:rtype: int
16+
"""
17+
def getPrefix(pattern):
18+
prefix = [-1]*len(pattern)
19+
j = -1
20+
for i in xrange(1, len(pattern)):
21+
while j+1 > 0 and pattern[j+1] != pattern[i]:
22+
j = prefix[j]
23+
if pattern[j+1] == pattern[i]:
24+
j += 1
25+
prefix[i] = j
26+
return prefix
27+
28+
prefix = getPrefix(pattern)
29+
i = j = -1
30+
while True:
31+
d = stream.next()
32+
i += 1
33+
while j+1 > 0 and pattern[j+1] != d:
34+
j = prefix[j]
35+
if pattern[j+1] == d:
36+
j += 1
37+
if j+1 == len(pattern):
38+
return i-j
39+
return -1

0 commit comments

Comments
 (0)