forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0763-partition-labels.cpp
38 lines (31 loc) · 932 Bytes
/
0763-partition-labels.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/*
Partition string so each letter appears in at most 1 part, return sizes
Ex. s = "ababcbacadefegdehijhklij" -> [9,7,8]
Greedy: determine last occurrence of each char, then loop thru & get sizes
Time: O(n)
Space: O(1)
*/
class Solution {
public:
vector<int> partitionLabels(string s) {
int n = s.size();
// {char -> last index in s}
vector<int> lastIndex(26);
for (int i = 0; i < n; i++) {
lastIndex[s[i] - 'a'] = i;
}
int size = 0;
int end = 0;
vector<int> result;
for (int i = 0; i < n; i++) {
size++;
// constantly checking for further indices if possible
end = max(end, lastIndex[s[i] - 'a']);
if (i == end) {
result.push_back(size);
size = 0;
}
}
return result;
}
};