题干:
字符串
S
由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一字母最多出现在一个片段中。返回一个表示每个字符串片段的长度的列表。示例:
输入:S = "ababcbacadefegdehijhklij"
输出:[9,7,8]
解释:
划分结果为 "ababcbaca", "defegde", "hijhklij"。
每个字母最多出现在一个片段中。
像 "ababcbacadefegde", "hijhklij" 的划分是错误的,因为划分的片段数较少。
public class 划分字母区间 {
public static void main(String[] args) {
String s = "ababcbacadefegdehijhklij";
String s2 = "caedbdedda";
List<Integer> ans = new ArrayList<>();
ans = partitionLabels(s2);
for (Integer an : ans) {
System.out.println(an);
}
}
public static List<Integer> partitionLabels(String s) {
List<Integer> ans = new ArrayList<>();
int max=0;
int lastlen=0;
for(int i=0;i<s.length(); i=max+1){
int now = s.lastIndexOf(s.charAt(i));
if(now>max) max = now;
for(int j=i+1;j<max;j++){
max = Math.max(s.lastIndexOf(s.charAt(j)),max);
}
ans.add(max+1-lastlen);
lastlen = max+1;
}
return ans;
}
}
抓住题干两个关键信息,“划分为尽可能多的片段”,“每个字母最多出现在一个片段中”。
看完题目的第一个想法是通过string函数的lastIndexof函数,去查找每个字符最后出现的索引,然后以此索引作为分段边界。若在分段边界内出现某个字符最后出现的索引大于边界时,边界拓宽为此索引位置;若在分段边界内没有字符最后出现的索引大于边界时,此边界作为实际的分段边界,边界+1再减去上一个子序列的长度作为此子序列的长度,保存。
按照上述思路得到的答案可以保证每个片段中的长度一定是符合要求的最短长度,如果取更短的片段,则一定会出现同一个字母出现在多个片段中的情况。