A string S of lowercase letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts.
class Solution {
public List<Integer> partitionLabels(String S) {
if(S.length()==0)return null;
List<Integer> list = new ArrayList<>();//采用list存储结果,list不定长,利用add方法在链表后添加元素int[] word = newint[26];
for(int i = 0;i<S.length();i++){
word[S.charAt(i)-'a']=i;//word数组用来存储每个字母的最大索引
}
int start = 0,end = 0;//标记分割成小组的开始索引和结束索引for(int i=0;i<S.length();i++){//遍历S中的所有字母
end = Math.max(end,word[S.charAt(i)-'a']);//将结束索引与遍历的字母的最大索引比较大小,取最大的值作为该小组的最大索引if(end==i){//当遍历到这个最大索引时,证明其左边字母的全部均包含在内,该索引点即为分割点list.add(end-start+1);
start=end+1;//开始点为分割点的下一个字母,进行下一步的遍历
}
}
returnlist;
}
}