力扣算法题-763.划分字母区间 C语言实现

it2026-04-23  7

题目

字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一个字母只会出现在其中的一个片段。返回一个表示每个字符串片段的长度的列表。

示例 1: 输入:S = “ababcbacadefegdehijhklij” 输出:[9,7,8] 解释: 划分结果为 “ababcbaca”, “defegde”, “hijhklij”。 每个字母最多出现在一个片段中。 像 “ababcbacadefegde”, “hijhklij” 的划分是错误的,因为划分的片段数较少。

提示: S的长度在[1, 500]之间。 S只包含小写字母 ‘a’ 到 ‘z’ 。

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/partition-labels

思路

区间内的最远位置,是可以满足“同一个字母只会出现在其中的一个片段”的最小长度。据此可知: 1、首先获取每个字符的最大下标; 2、遍历字符串,获取片段的结束位置,知道遍历的下标和结束位置相同。

程序

/** * Note: The returned array must be malloced, assume caller calls free(). */ int* partitionLabels(char * S, int* returnSize){ int ilen = strlen(S), k=0,ibgn=0,iend=0; int* b = (int*)malloc(sizeof(int)*ilen); int a[26] = {0}; /*记录每个字符的结束位*/ for(int i=0;i<ilen;i++){ a[S[i]-'a'] = i; } /*遍历字符串*/ for(int i=0;i<ilen;i++){ iend = a[S[i]-'a'] > iend ? a[S[i]-'a'] : iend; /*序号和结束位置相等,可以表示同一个字符都在这个区间内的最小区间*/ if(i == iend){ b[k++] = iend - ibgn + 1; ibgn = i+1; } } (*returnSize) = k; return b; }
最新回复(0)