You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part.
Note that the partition is done so that after concatenating all the parts in order, the resultant string should be s.
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.
Example 2:
Input: s = "eccbbbbdec"
Output: [10]
Constraints:
1 <= s.length <= 500sconsists of lowercase English letters.
答案
func partitionLabels(s string) []int {
fnt := [26]int{}
res := make([]int, 0)
sum := 0
for _, e := range s {
fnt[e-'a']++
}
m := make(map[rune]int)
count := 0
for i, e := range s {
//m记录当前区间的字符类型数
_, ok := m[e]
if !ok {
m[e] = 1
}
fnt[e-'a']--
//后面再也没有该字符
if fnt[e-'a'] == 0 {
count++
}
//区间内的字符都不会在后面出现了,可以切割了
if count == len(m) {
//当前区间的字符,在后面均不会出现了
res = append(res, i-sum+1)
sum += res[len(res)-1]
//重新置0
count = 0
m = make(map[rune]int)
}
}
return res
}
更好的做法
func partitionLabels(s string) []int {
fnt := [26]int{}
res := make([]int, 0)
sum := 0
last := 0
//记录字符最后出现的下标
for i, e := range s {
fnt[e-'a'] = i
}
max := func(a,b int) int {
if a > b {
return a
}
return b
}
for i, e := range s {
last = max(last,fnt[e-'a'])
if last == i {
res = append(res,i-sum+1)
sum += res[len(res)-1]
}
}
return res
}