forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
maximum-number-of-removable-characters.py
65 lines (60 loc) · 1.72 KB
/
maximum-number-of-removable-characters.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
# Time: O(rlogn)
# Space: O(r)
# if r = O(1), this is better
class Solution(object):
def maximumRemovals(self, s, p, removable):
"""
:type s: str
:type p: str
:type removable: List[int]
:rtype: int
"""
def check(s, p, removable, x):
lookup = set(removable[i] for i in xrange(x))
j = 0
for i in xrange(len(s)):
if i in lookup or s[i] != p[j]:
continue
j += 1
if j == len(p):
return True
return False
left, right = 0, len(removable)
while left <= right:
mid = left + (right-left)//2
if not check(s, p, removable, mid):
right = mid-1
else:
left = mid+1
return right
# Time: O(rlogn)
# Space: O(n)
# if r = O(n), this is better
class Solution2(object):
def maximumRemovals(self, s, p, removable):
"""
:type s: str
:type p: str
:type removable: List[int]
:rtype: int
"""
def check(s, p, lookup, x):
j = 0
for i in xrange(len(s)):
if lookup[i] <= x or s[i] != p[j]:
continue
j += 1
if j == len(p):
return True
return False
lookup = [float("inf")]*len(s)
for i, r in enumerate(removable):
lookup[r] = i+1
left, right = 0, len(removable)
while left <= right:
mid = left + (right-left)//2
if not check(s, p, lookup, mid):
right = mid-1
else:
left = mid+1
return right