763. Partition Labels 分区标签
时间:2022-05-04 09:10
A string Note:
给出一个小写字母的字符串S.我们想把这个字符串分成尽可能多的部分,这样每个字母最多只出现一个部分,并返回一个表示这些部分大小的整数列表。S
will have length in range [1, 500]
.S
will consist of lowercase letters (‘a‘
to ‘z‘
) only./**
* @param {string} S
* @return {number[]}
*/
var partitionLabels = function (S) {
let posDict = {};
for (let i = 0; i < S.length; i++) {
let char = S[i];
if (posDict[char]) {
posDict[char].end = i;
} else {
posDict[char] = { start: i, end: i };
}
}
let res = [];
let min = max = 0;
for (let i in posDict) {
let start = posDict[i].start;
let end = posDict[i].end;
if (start > max) {
res.push(max - min + 1);
[min, max] = [start, end];
} else {
max = Math.max(max, end);
}
}
res.push(max - min + 1);
return res;
};
let S = "ababcbacadefegdehijhklij";
let res = partitionLabels(S);
console.log(res);