forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0763-partition-labels.js
69 lines (54 loc) · 1.49 KB
/
0763-partition-labels.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
/**
* @param {string} s
* @return {number[]}
*/
var partitionLabels = function (s) {
var lastIndex = {}, // char -> last index in s
res = [],
size = 0,
end = 0;
for (var i in s) {
lastIndex[s[i]] = i;
}
for (var i in s) {
var c = s[i];
size++;
end = Math.max(end, lastIndex[c]);
if (i === String(end)) {
res.push(size);
size = 0;
}
}
return res;
};
/**
* https://leetcode.com/problems/partition-labels/
* Time O(N) | Space(1)
* @param {string} S
* @return {number[]}
*/
var partitionLabels = function(S) {
const lastSeen = getLast(S);
return getAns(S, lastSeen);
};
const getLast = (S, lastSeen = []) => {
for (const index in S) {/* Time O(N) */
const code = getCode(S[Number(index)]);
lastSeen[code] = Number(index);/* Space O(1) */
}
return lastSeen;
};
const getCode = (char ) => char.charCodeAt(0) - 'a'.charCodeAt(0);
const getAns = (S, lastSeen, left = 0, right = 0, labels = []) => {
for (const index in S) {/* Time O(N) */
const code = getCode(S[Number(index)]);
const lastSeenAt = lastSeen[code];
right = Math.max(right, lastSeenAt);
const isEqual = Number(index) === right;
if (!isEqual) continue;
const placement = (Number(index) - left) + 1;
labels.push(placement);
left = Number(index) + 1;
};
return labels;
}