|
| 1 | +# Time: O(rlogn) |
| 2 | +# Space: O(r) |
| 3 | + |
| 4 | +# if r = O(1), this is better |
| 5 | +class Solution(object): |
| 6 | + def maximumRemovals(self, s, p, removable): |
| 7 | + """ |
| 8 | + :type s: str |
| 9 | + :type p: str |
| 10 | + :type removable: List[int] |
| 11 | + :rtype: int |
| 12 | + """ |
| 13 | + def check(s, p, removable, x): |
| 14 | + lookup = set(removable[i] for i in xrange(x)) |
| 15 | + j = 0 |
| 16 | + for i in xrange(len(s)): |
| 17 | + if i in lookup or s[i] != p[j]: |
| 18 | + continue |
| 19 | + j += 1 |
| 20 | + if j == len(p): |
| 21 | + return True |
| 22 | + return False |
| 23 | + |
| 24 | + left, right = 0, len(removable) |
| 25 | + while left <= right: |
| 26 | + mid = left + (right-left)//2 |
| 27 | + if not check(s, p, removable, mid): |
| 28 | + right = mid-1 |
| 29 | + else: |
| 30 | + left = mid+1 |
| 31 | + return right |
| 32 | + |
| 33 | + |
| 34 | +# Time: O(rlogn) |
| 35 | +# Space: O(n) |
| 36 | +# if r = O(n), this is better |
| 37 | +class Solution2(object): |
| 38 | + def maximumRemovals(self, s, p, removable): |
| 39 | + """ |
| 40 | + :type s: str |
| 41 | + :type p: str |
| 42 | + :type removable: List[int] |
| 43 | + :rtype: int |
| 44 | + """ |
| 45 | + def check(s, p, lookup, x): |
| 46 | + j = 0 |
| 47 | + for i in xrange(len(s)): |
| 48 | + if lookup[i] <= x or s[i] != p[j]: |
| 49 | + continue |
| 50 | + j += 1 |
| 51 | + if j == len(p): |
| 52 | + return True |
| 53 | + return False |
| 54 | + |
| 55 | + lookup = [float("inf")]*len(s) |
| 56 | + for i, r in enumerate(removable): |
| 57 | + lookup[r] = i+1 |
| 58 | + left, right = 0, len(removable) |
| 59 | + while left <= right: |
| 60 | + mid = left + (right-left)//2 |
| 61 | + if not check(s, p, lookup, mid): |
| 62 | + right = mid-1 |
| 63 | + else: |
| 64 | + left = mid+1 |
| 65 | + return right |
0 commit comments