Leetcode763. 划分字母区间(贪心)

问题描述

字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一字母最多出现在一个片段中。返回一个表示每个字符串片段的长度的列表。

示例:

输入:S = "ababcbacadefegdehijhklij"
输出:[9,7,8]
解释:
划分结果为 "ababcbaca", "defegde", "hijhklij"。
每个字母最多出现在一个片段中。
像 "ababcbacadefegde", "hijhklij" 的划分是错误的,因为划分的片段数较少。

代码

class Solution {
    public List<Integer> partitionLabels(String S) {
		 List<Integer> res=new ArrayList<Integer>();
		  int max;
		  int start=0;
		  while(start<S.length()) {
			  max=Math.max(S.indexOf((int)S.charAt(start),start+1), start);
		  for(int i=start;i<=max;i++) {
			  int temp=Math.max(S.indexOf((int)S.charAt(i),i+1), i);
				if(max<temp) {
					max=temp;
				}
		  }
		  res.add(max-start+1);
		  start=max+1;
		  }
		  return res;
	    }
}

原文地址:https://www.cnblogs.com/code-fun/p/14477946.html