-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathfind-pattern-in-infinite-stream-ii.py
More file actions
40 lines (36 loc) · 1019 Bytes
/
find-pattern-in-infinite-stream-ii.py
File metadata and controls
40 lines (36 loc) · 1019 Bytes
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
# Time: O(p + n)
# Space: O(p)
# Definition for an infinite stream.
class InfiniteStream:
def next(self):
pass
# kmp
class Solution(object):
def findPattern(self, stream, pattern):
"""
:type stream: InfiniteStream
:type pattern: List[int]
:rtype: int
"""
def getPrefix(pattern):
prefix = [-1]*len(pattern)
j = -1
for i in xrange(1, len(pattern)):
while j+1 > 0 and pattern[j+1] != pattern[i]:
j = prefix[j]
if pattern[j+1] == pattern[i]:
j += 1
prefix[i] = j
return prefix
prefix = getPrefix(pattern)
i = j = -1
while True:
d = stream.next()
i += 1
while j+1 > 0 and pattern[j+1] != d:
j = prefix[j]
if pattern[j+1] == d:
j += 1
if j+1 == len(pattern):
return i-j
return -1