-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path763_javascript.js
More file actions
69 lines (61 loc) · 1.63 KB
/
763_javascript.js
File metadata and controls
69 lines (61 loc) · 1.63 KB
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
// 字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一字母最多出现在一个片段中。返回一个表示每个字符串片段的长度的列表。
//
// 示例:
// 输入:S = "ababcbacadefegdehijhklij"
// 输出:[9,7,8]
// 解释:
// 划分结果为 "ababcbaca", "defegde", "hijhklij"。
// 每个字母最多出现在一个片段中。
// 像 "ababcbacadefegde", "hijhklij" 的划分是错误的,因为划分的片段数较少。
//
// 提示:
// S的长度在[1, 500]之间。
// S只包含小写字母 'a' 到 'z' 。
// 通过次数53,821提交次数70,267
/**
* @param {string} S
* @return {number[]}
*/
// 贪心
var partitionLabels = function (S) {
// 获取每个元素的区间范围
// 再合并区间
let arr = [];
for (let i = 0; i < S.length; i++) {
arr.push([S.indexOf(S[i]), S.lastIndexOf(S[i])]);
}
arr.sort((a, b) => a[0] - b[0]);
let end = arr[0][1];
let start = arr[0][0];
let res = [];
for (let j = 1; j < arr.length; j++) {
if (arr[j][0] > end) {
res.push(end - start + 1);
start = arr[j][0];
end = arr[j][1];
} else {
end = Math.max(end, arr[j][1]);
}
}
res.push(end - start + 1);
return res;
};
// Map 方法
var partitionLabels = function (S) {
// 获取每个元素最后一次的位置
let map = new Map();
for (let i = 0; i < S.length; i++) {
map.set(S[i], i);
}
let res = [],
end = 0,
start = 0;
for (let j = 0; j < S.length; j++) {
end = Math.max(end, map.get(S[j]));
if (end == j) {
res.push(end - start + 1);
start = j + 1;
}
}
return res;
};