A string S
of lowercase letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts.
Example 1:
Input: S = "ababcbacadefegdehijhklij" Output: [9,7,8] Explanation: The partition is "ababcbaca", "defegde", "hijhklij". This is a partition so that each letter appears in at most one part. A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts.
Note:
S
will have length in range[1, 500]
.S
will consist of lowercase letters (‘a‘
to‘z‘
) only.
给出一个小写字母的字符串S.我们想把这个字符串分成尽可能多的部分,这样每个字母最多只出现一个部分,并返回一个表示这些部分大小的整数列表。
/**
* @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);