2020-05-16 力扣763. 划分字母区间
解析
很容易想到要找到字符的最远位置。贪心法
int* partitionLabels(char * s, int* returnSize){
int length = strlen(s);
int location[26] = {0};
for (int i = 0; i < length; ++i) { // 找到每个字符的最远距离
location[s[i]-'a'] = i;
}
int maxIndex = 0; // 记录片段中字符出现的最远位置,如果片段中没有重复的则最远的就是自己
int *result = (int*)malloc(sizeof(int) * (length));
*returnSize = 0;
int left = 0;
int right = 0;
while (right < length) {
maxIndex = location[s[right]-'a'] > maxIndex ? location[s[right]-'a'] : maxIndex;
if (right == maxIndex) {
result[*returnSize] = right - left + 1;
(*returnSize)++;
left = right + 1;
}
right++;
}
return result;
}