763. Partition Labels
Input: S = "ababcbacadefegdehijhklij"
Output: [9,7,8]
Explanation:
The partition is "ababcbaca", "defegde", "hijhklij".
This is a partition so that each letter appears in at most one part.
A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts.解题要点:
class Solution {
public List<Integer> partitionLabels(String S) {
int[] lastIndex = new int[26];
for(int i = 0; i < S.length(); i++){
lastIndex[S.charAt(i) - 'a'] = i;
}
List<Integer> res = new ArrayList<>();
int index1 = 0;
while(index1 < S.length()){
int index2 = index1;
for(int i = index1; i < S.length() && i <= index2; i++){
int index = lastIndex[S.charAt(i) - 'a'];
index2 = Math.max(index, index2);
}
res.add(index2 - index1 + 1);
index1 = index2 + 1;
}
return res;
}
}Last updated