763. Partition Labels
Problem
Split s into as many parts as possible so that each letter appears in at most one part. Return the part sizes in order.
Example: "ababcbacadefegdehijhklij" → [9,7,8]
Record each letter's last index. Extend the current part's end to the max last-index of letters seen; when i == end, cut.
a b a b c b a c a | d e f e g d e | h i j h k l i j
last(a)=8 -> part ends at 8 once all letters inside end by 8
Complexity: O(n).
class Solution:
def partitionLabels(self, s: str) -> List[int]:
last = {ch: i for i, ch in enumerate(s)}
res, start, end = [], 0, 0
for i, ch in enumerate(s):
end = max(end, last[ch])
if i == end:
res.append(end - start + 1)
start = i + 1
return res
assert Solution().partitionLabels("ababcbacadefegdehijhklij") == [9, 7, 8]
assert Solution().partitionLabels("eccbbbbdec") == [10]
class Solution {
public List<Integer> partitionLabels(String s) {
int[] last = new int[26];
for (int i = 0; i < s.length(); i++) last[s.charAt(i) - 'a'] = i;
List<Integer> res = new ArrayList<>();
int start = 0, end = 0;
for (int i = 0; i < s.length(); i++) {
end = Math.max(end, last[s.charAt(i) - 'a']);
if (i == end) { res.add(end - start + 1); start = i + 1; }
}
return res;
}
}
func partitionLabels(s string) []int {
last := [26]int{}
for i := 0; i < len(s); i++ {
last[s[i]-'a'] = i
}
res := []int{}
start, end := 0, 0
for i := 0; i < len(s); i++ {
end = max(end, last[s[i]-'a']) // the part must reach every letter's last occurrence
if i == end {
res = append(res, end-start+1)
start = i + 1
}
}
return res
}