763. Partition Labels
Problem
Tags: Hash Table
, Two Pointers
, String
, Greedy
You are given a string s
. We want to partition the string into as many parts as possible so that each letter appears in at most one part.
Note that the partition is done so that after concatenating all the parts in order, the resultant string should be s
.
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.
Example 2:
Input: s = "eccbbbbdec"
Output: [10]
Constraints:
1 <= s.length <= 500
s
consists of lowercase English letters.
Code
C
// 763. Partition Labels (10/9/54187)
// Runtime: 0 ms (94.37%) Memory: 5.85 MB (33.80%)
#define MAX(a, b) ((a > b) ? a : b)
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* partitionLabels (char* s, int* return_size) {
int len = strlen(s);
int last[26] = { -1 };
for (int i = 0; s[i] != '\0'; i++) {
last[s[i] - 'a'] = i;
}
int* slices = (int*)malloc(26 * sizeof(int));
int size = 0;
int from = -1, farthest = -1;
for (int i = 0; s[i] != '\0'; i++) {
if (from == -1) {
from = i;
}
farthest = MAX(farthest, last[s[i] - 'a']);
if (i == farthest) {
slices[size++] = farthest - from + 1;
from = -1;
}
}
*return_size = size;
return slices;
}
TS
// 763. Partition Labels (10/14/54187)
// Runtime: 89 ms (65.57%) Memory: 44.23 MB (90.16%)
function partitionLabels(s: string): number[] {
const slices = [] as number[];
let from = -1, to = -1;
for (let i = 0; i < s.length; i++) {
if (from === -1) {
from = i;
}
to = Math.max(to, s.lastIndexOf(s[i]));
if (i === to) {
slices.push(to - from + 1);
from = -1;
}
}
return slices;
};