题目:
字符串 S 由⼩写字⺟组成。我们要把这个字符串划分为尽可能多的⽚段,同⼀字⺟最多出现在⼀个⽚段中。返回⼀
个表示每个字符串⽚段的⻓度的列表。
示例:
输⼊:S = “ababcbacadefegdehijhklij”
输出:[9,7,8]
解释:
划分结果为 “ababcbaca”, “defegde”, “hijhklij”。
每个字⺟最多出现在⼀个⽚段中。
像 “ababcbacadefegde”, “hijhklij” 的划分是错误的,因为划分的⽚段数较少。
let S = "asdfhgk;weryotpqowiezvb,znxc"
let map = new Map()
const ls=S.length
for (let i = 0; i <ls; i++) {
const e = S[i];
let t = map.get(e) || []
if (t) {
t.push(i)
} else {
t = []
}
map.set(e, t)
}
let arr = Array.from(map.values())
let temp = arr[0]
let res = []
for (let j = 1; j < arr.length; j++) {
const l = temp.length - 1
const aj=arr[j].length - 1
if (arr[j][0] < temp[l] && arr[j][aj] > temp[l]) {
temp.push(arr[j][aj])
} else if (arr[j][0] < temp[l] && arr[j][aj] < temp[l]) {
continue
} else {
res.push(temp[l])
temp = arr[j]
}
}
console.log(res);
//这里再对res稍做处理一下就行了