字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一字母最多出现在一个片段中。返回一个表示每个字符串片段的长度的列表。
示例:
输入:S = “ababcbacadefegdehijhklij” 输出:[9,7,8] 解释: 划分结果为 “ababcbaca”,
“defegde”, “hijhklij”。 每个字母最多出现在一个片段中。 像 “ababcbacadefegde”,
“hijhklij” 的划分是错误的,因为划分的片段数较少。
本题与其说是贪心,更像是一道模拟题,我们需要通过切割来获得最多的字符串(限制条件是每个字母最多出现在一个片段中),那么我们就通过一趟扫描记录每个字母的最远位置,再经过一趟扫描,维护一个idx,每次更新当前字母的最远位置,一旦到达当前最远位置,则可以进行切割,last维护了上一段的尾部index,以方便我们计算长度。
public List<Integer> partitionLabels(String s) {
int[] buckets=new int[26];//类似桶
char[] chars=s.toCharArray();
List<Integer> res=new ArrayList<>();
for (int i = 0; i < chars.length; i++) {
buckets[chars[i]-'a']=i;
}//一次遍历记录每个元素的最远位置
int idx=0;
int last=-1;//记录当前的last
for (int i = 0; i < chars.length; i++) {
idx=Math.max(idx,buckets[chars[i]-'a']);
if(i==idx){
res.add(i-last);
last=idx;
}
}
return res;
}