-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
find-beautiful-indices-in-the-given-array-ii.py
89 lines (80 loc) · 2.63 KB
/
find-beautiful-indices-in-the-given-array-ii.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
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
77
78
79
80
81
82
83
84
85
86
87
88
89
# Time: O(n), x = len(KMP(s, a)), y = len(KMP(s, b))
# Space: O(min(a + b + x + y, n))
# kmp, two pointers
class Solution(object):
def beautifulIndices(self, s, a, b, k):
"""
:type s: str
:type a: str
:type b: str
:type k: int
:rtype: List[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
def KMP(text, pattern):
prefix = getPrefix(pattern)
j = -1
for i in xrange(len(text)):
while j+1 > 0 and pattern[j+1] != text[i]:
j = prefix[j]
if pattern[j+1] == text[i]:
j += 1
if j+1 == len(pattern):
yield i-j
j = prefix[j]
result = []
if not (len(a) <= len(s) and len(b) <= len(s)):
return result
lookup = list(KMP(s, b))
j = 0
for i in KMP(s, a):
while j < len(lookup) and lookup[j] < i-k:
j += 1
if j < len(lookup) and lookup[j] <= i+k:
result.append(i)
return result
# Time: O(n + xlogy), x = len(KMP(s, a)), y = len(KMP(s, b))
# Space: O(n)
import bisect
# kmp, binary search
class Solution2(object):
def beautifulIndices(self, s, a, b, k):
"""
:type s: str
:type a: str
:type b: str
:type k: int
:rtype: List[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
def KMP(text, pattern):
prefix = getPrefix(pattern+'#'+text)
return ((i-(len(pattern)+1))-(len(pattern)-1) for i in xrange((len(pattern)+1)+(len(pattern)-1) , len(prefix)) if prefix[i]+1 == len(pattern))
result = []
if not (len(a) <= len(s) and len(b) <= len(s)):
return result
lookup = list(KMP(s, b))
j = 0
for i in KMP(s, a):
j = bisect.bisect_left(lookup, i-k)
if j < len(lookup) and lookup[j] <= i+k:
result.append(i)
return result