763. Partition Labels


Last updated


Last updated
part_max_index = 8
012345678 9012345
"ababcbaca | defegde | hijhklij"
index = 0, map get(a) = 8, maxPartIndex = 8
index = 1, map get(b) = 5
index = 2, map get(a) = 8
index = 3, map get(b) = 5
index = 4, map get(c) = 7
index = 5, map get(b) = 5
index = 6, map get(a) = 8
index = 7, map get(c) = 7
index = 8, map.get(a) = 8 => index == maxPartIndex == 8
index = 9, map.get(d) = 14
index = 10, map.get(e) = 15
index = 11, map.get(f) = 11
index = 12, map.get(e) = 15
index = 13, map.get(g) = 13
index = 14, map.get(d) = 14
index = 15, map.get(e) = 15
index = 16, map.get(h) = 19class Solution {
public List<Integer> partitionLabels(String S) {
// record the char last index
// a index 8,
// if loop until max end equla current index, means it's a part, save len
// s = index + 1,
int map[] = new int[26]; // S will consist of lowercase English letters ('a' to 'z') only.
for (int i = 0; i < S.length(); i++) {
char c = S.charAt(i);
map[c - 'a'] = i;
}
List<Integer> res = new ArrayList<>();
int start = 0;
int end = 0;
for (int i = 0; i < S.length(); i++) {
end = Math.max(end, map[S.charAt(i) - 'a']); //注意要更新最大的 end
if (end == i) {
res.add(i - start + 1);
start = i + 1;
}
}
return res;
}
}