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.
Example 1:
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.
思路:
- traverse the string record the last index of each char.
- using pointer to record end of the current sub string.
class Solution {
public List<Integer> partitionLabels(String s) {
List<Integer> list = new ArrayList<>();
int[] count = new int[26];
for(int i = 0; i < s.length(); i++) {
count[s.charAt(i) - 'a'] = i;
}
int start = 0;
int last = 0;
// start....last;
for(int i = 0; i < s.length(); i++) {
last = Math.max(last, count[s.charAt(i) - 'a']);
if(last == i) {
list.add(last - start + 1);
start = last + 1;
}
}
return list;
}
}