贪心----4.划分字母区间
763. 划分字母区间 - 力扣(LeetCode)
/**
首先遍历一遍字符串,记录每个字符最后出现的位置(不断迭代字符出现的位置即可)
再次遍历字符数组,维护一个变量end,代表已出现元素最后一个位置,
当end == i时,代表当前所有已经出现元素都囊括其中
*/
class Solution {/**首先遍历一遍字符串,记录每个字符最后出现的位置(不断迭代字符出现的位置即可)再次遍历字符数组,维护一个变量end,代表已出现元素最后一个位置,当end == i时,代表当前所有已经出现元素都囊括其中*/private List<Integer> result = new ArrayList<>();public List<Integer> partitionLabels(String s) {//将字符串转化为字符数组,便于得出字符出现的位置char c[] = s.toCharArray();//用于记录元素最后出现位置int lastIndex[] = new int[26];//遍历字符数组,得出每个元素最后出现位置for(int i = 0; i < c.length; i++) {lastIndex[c[i] - 'a'] = i;}//再次遍历字符数组,维护一个变量end,记录已出现元素的最后一个位置,int end = 0,start = 0;for(int i = 0; i < c.length; i++) {//已出现元素的最后一个位置end = Math.max(end,lastIndex[c[i] - 'a']);//当end == i时,代表当前所有已经出现元素都囊括其中,即得出一个片段if(end == i) {result.add(end - start + 1);start = end + 1; //下一个片段的开始位置}}return result;}
}