forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1898-maximum-number-of-removable-characters.js
95 lines (79 loc) · 1.57 KB
/
1898-maximum-number-of-removable-characters.js
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
90
91
92
93
94
95
/**
* https://leetcode.com/problems/maximum-number-of-removable-characters/
*
* Brute force
* Time O(removable.length * s.length) | Space O(n)
* @param {string} s
* @param {string} p
* @param {number[]} removable
* @return {number}
*/
var maximumRemovals1 = function(s, p, removable) {
let k = 0;
// removable.reverse();
s = s.split('');
p = p.split('');
for (let i = 0; i < removable.length; i++) {
s[removable[i]] = -1;
if (isSubSet1(s, p)) {
k++;
continue;
}
return k;
}
return k;
};
// helper function.
function isSubSet1(s, p) {
let i = 0;
let j = 0;
while (i < s.length && j < p.length) {
if (s[i] === p[j]) {
i++;
j++;
} else {
i++;
}
}
return j === p.length;
}
/**
*
* Binary Search
* n = length of string, k = length of removable
* Time O(log(k)*n) | Space O(1)
* @param {string} s
* @param {string} p
* @param {number[]} removable
* @return {number}
*/
var maximumRemovals = function(s, p, removable) {
let left = 0;
let right = removable.length - 1;
let k = 0;
while (left <= right) {
const mid = (left + right) >> 1;
const hash = new Set(removable.slice(0, mid + 1));
if (isSubSet(hash, s, p)) {
k = Math.max(k, mid + 1);
left = mid + 1;
continue;
}
right = mid - 1;
}
return k;
};
// helper function.
function isSubSet(hash, s, p) {
let i = 0;
let j = 0;
while (i < s.length && j < p.length) {
if (s[i] === p[j] && !hash.has(i)) {
i++;
j++;
continue;
}
i++;
}
return j === p.length;
}