/**
* NOTE:(763) 字符串 S 由小写字母组成, 将这个字符串划分为尽可能多的片段, 同一个字母只会出现在其中一个片段,
* 放回一个表示每个字符串片段的长度的列表
* input: S = "ababcbacadefegdehijhklij"
* output: [9,7,8]
* example: "ababcbaca", "defegde", "hijhklij"
*/
var partitionLabels = function (S) {
let obj = {}
let result = []
for (let i = 0, len = S.length; i < len; i++) {
obj[S[i]] = i
}
let m = 0
let max = 0
for (let i = 0, len = S.length; i < len; i++) {
let char = S[i]
let charIndex = obj[char]
max = Math.max(charIndex, max)
// console.log(max, charIndex, i)
if (max === i) {
let r = S.slice(m, max + 1)
result.push(r.length)
m = i + 1
}
}
console.log(result)
return result
};
partitionLabels("aebbedaddc")
// partitionLabels("ababcbacadefegdehijhklij")
网友评论