-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.py
More file actions
76 lines (49 loc) · 1.49 KB
/
Copy pathsolution.py
File metadata and controls
76 lines (49 loc) · 1.49 KB
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
class Solution:
# Function to build LPS array
def buildLPS(self, b):
m = len(b)
# Create LPS array
lps = [0] * m
# Length of previous longest prefix suffix
length = 0
i = 1
while i < m:
# Matching elements
if b[i] == b[length]:
length += 1
lps[i] = length
i += 1
else:
# Try smaller prefix
if length != 0:
length = lps[length - 1]
else:
lps[i] = 0
i += 1
return lps
def search(self, a, b):
n = len(a)
m = len(b)
# Build LPS array
lps = self.buildLPS(b)
# Store answer
ans = []
i = 0
j = 0
while i < n:
# Elements match
if a[i] == b[j]:
i += 1
j += 1
# Full pattern matched
if j == m:
ans.append(i - m)
# Continue searching
j = lps[j - 1]
# Mismatch
elif i < n and a[i] != b[j]:
if j != 0:
j = lps[j - 1]
else:
i += 1
return ans