forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0763-partition-labels.c
More file actions
26 lines (21 loc) · 824 Bytes
/
0763-partition-labels.c
File metadata and controls
26 lines (21 loc) · 824 Bytes
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
int* partitionLabels(char* s, int* returnSize) {
int* result = NULL;
int* lastOccurrence = (int*)calloc(26, sizeof(int)); // Store the last occurrence index of each character
// Find the last occurrence index of each character
for (int i = 0; s[i] != '\0'; i++) {
lastOccurrence[s[i] - 'a'] = i;
}
int start = 0, end = 0; // Pointers to track the current partition
*returnSize = 0;
for (int i = 0; s[i] != '\0'; i++) {
end = (end > lastOccurrence[s[i] - 'a']) ? end : lastOccurrence[s[i] - 'a'];
if (i == end) {
(*returnSize)++;
result = (int*)realloc(result, sizeof(int) * (*returnSize));
result[(*returnSize) - 1] = end - start + 1;
start = end + 1;
}
}
free(lastOccurrence);
return result;
}