划分字母区间
七崽爱吃小饼干2026/01/31阅读 0
划分字母区间
给你一个字符串 s 。我们要把这个字符串划分为尽可能多的片段,同一字母最多出现在一个片段中。例如,字符串 "ababcc" 能够被分为 ["abab", "cc"],但类似 ["aba", "bcc"] 或 ["ab", "ab", "cc"] 的划分是非法的。
注意,划分结果需要满足:将所有划分结果按顺序连接,得到的字符串仍然是 s 。
返回一个表示每个字符串片段的长度的列表。
示例 1:
codeType
输入:s = "ababcbacadefegdehijhklij"
输出:[9,7,8]
解释:
划分结果为 "ababcbaca"、"defegde"、"hijhklij" 。
每个字母最多出现在一个片段中。
像 "ababcbacadefegde", "hijhklij" 这样的划分是错误的,因为划分的片段数较少。
示例 2:
codeType
输入:s = "eccbbbbdec"
输出:[10]
提示:
- 1 <= s.length <= 500
- s 仅由小写英文字母组成
解法
ts
function partitionLabels(s: string): number[] {
// 找到每种字符在字符串的第一个位置和最后一个位置,视为区间
// 将所有相交的区间进行合并即可
const map = new Map<string, {
start: number
end: number
}>()
const n = s.length
// 查找每个字母的第一个出现位置和最后一个出现位置
for(let i = 0; i < n; i++){
if(map.has(s[i])){
map.set(s[i], {
start: map.get(s[i]).start,
end: i
})
}else{
map.set(s[i], {
start: i,
end: i
})
}
}
const Intervals: {
start: number
end: number
}[] = Array.from(map.values()).sort((a, b) => a.start - b.start) // 按照start升序排列
// 合并区间
const resIntervals = []
for(let i = 0; i < Intervals.length; i++){
if(resIntervals.length === 0){
resIntervals.push(Intervals[i])
}else{
const lastInterval = resIntervals[resIntervals.length - 1]
if(lastInterval.end < Intervals[i].start){ // 不相交
resIntervals.push(Intervals[i])
}else{
lastInterval.end = Math.max(lastInterval.end, Intervals[i].end) // 合并区间
}
}
}
// 区间转长度
return resIntervals.map(interval => interval.end - interval.start + 1)
};