classSolution{publicList<Integer>partitionLabels(String s){//使用HashMap记录每个字符出现的最大索引值Map<Character,Integer> map =newHashMap<>();// filling impact of character'sfor(int i =0; i < s.length(); i++){char ch = s.charAt(i);
map.put(ch, i);}// making of resultList<Integer> res =newArrayList<>();int prev =-1;int max =0;for(int i =0; i < s.length(); i++){char ch = s.charAt(i);//ch是当前遍历的字符//取出当前字符出现的最大索引和max中的最大值
max =Math.max(max, map.get(ch));//遍历到最大值,表示i之前的所有不同种类字符都被包含了,否则 max > i,表示还存在字符没有被遍历完if(max == i){// partition time,将长度返回,并更新起始位置prev
res.add(max - prev);
prev = max;}}return res;}}
3.合并区间
classSolution{publicint[][]merge(int[][] intervals){if(intervals ==null|| intervals.length ==0)returnnewint[][]{};// 按区间的 start 升序排列Arrays.sort(intervals,Comparator.comparingInt(a -> a[0]));List<int[]> res =newArrayList<>();//将第一个元素加入到res中
res.add(intervals[0]);// 注意从1开始for(int i=1; i<intervals.length; i++){int[] curr = intervals[i];// res 中最后一个元素的引用int[] last = res.get(res.size()-1);if(curr[0]<= last[1]){//当前的起始 < 上一个结束,表示相交// 找到最大的 end
last[1]=Math.max(last[1], curr[1]);}else{//否则不相交// 处理下一个待合并区间
res.add(curr);}}return res.toArray(newint[res.size()][]);}}