763.划分字母区间
字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一字母最多出现在一个片段中。返回一个表示每个字符串片段的长度的列表。
示例:
- 输入:S = “ababcbacadefegdehijhklij”
- 输出:[9,7,8]
解释:
划分结果为 “ababcbaca”, “defegde”, “hijhklij”。
每个字母最多出现在一个片段中。
像 “ababcbacadefegde”, “hijhklij” 的划分是错误的,因为划分的片段数较少。
提示:
- S的长度在[1, 500]之间。
- S只包含小写字母 ‘a’ 到 ‘z’ 。
先找到和最后一个和首字母相同的字母的位置,记为end,截取 [0,end]字符串temp,从end+1位继续找,在这个字符串temp中包含这个这个字符,则这个区间没有结束!!!end记为这个元素的位置,字符串temp更新,直到找到所有在[0,end]中出现的元素都在这个区间中了, 0更新为 end +1 继续找和end + 1位相同的字母。
package com.programmercarl.greed;
import java.util.ArrayList;
import java.util.List;
/**
* @ClassName PartitionLabels
* @Descriotion TODO
* @Author nitaotao
* @Date 2022/7/17 11:40
* @Version 1.0
* https://leetcode.cn/problems/partition-labels/
* 763. 划分字母区间
**/
public class PartitionLabels {
public List<Integer> partitionLabels(String s) {
List<Integer> result = new ArrayList<Integer>();
int end = 1;
//此时end为最后出现的首字母位置
for (int i = 0; i < s.length(); ) {
//找到最后出现的首字母的位置end
int k = i;
for (; k < s.length(); k++) {
if (s.charAt(k) == s.charAt(i)) {
end = k;
}
}
String temp = s.substring(i, end + 1);
for (int j = end + 1; j < s.length(); j++) {
if (temp.indexOf(s.charAt(j)) != -1) {
//如果之后还出现在[0,end]区间之外有内部元素
temp = s.substring(i, j+1);
end = j;
}
}
result.add(end - i + 1);
i = end + 1;
}
return result;
}
public static void main(String[] args) {
System.out.println(new PartitionLabels().partitionLabels("ababcbacadefegdehijhklij"));
}
}