一、题目描述
字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一字母最多出现在一个片段中。返回一个表示每个字符串片段的长度的列表。
示例 1:
输入:S = "ababcbacadefegdehijhklij"
输出:[9,7,8]
解释:
划分结果为 "ababcbaca", "defegde", "hijhklij"。
每个字母最多出现在一个片段中。
像 "ababcbacadefegde", "hijhklij" 的划分是错误的,因为划分的片段数较少。
二、解题
贪心算法
记录每个小写字母出现的最远距离,然后遍历字符串,使用双指针,记录最远的边界end,以及开始的边界start,当遍历的字符的下标等于记录的最远的边界,说明这个子串就是最长的,更新start。
class Solution {
public List<Integer> partitionLabels(String s) {
//贪心算法
//使用一个字母数组,记录该字母出现的最远位置
char[] schar = s.toCharArray();
List<Integer> res = new ArrayList<>();
int length = schar.length;
//26个小写字母
int[] index = new int[26];
for (int i = 0; i < length; i++) {
index[schar[i] - 'a'] = i;
}
//取边界的最大值
int start = 0,end = 0;
for (int i = 0; i < length; i++) {
end = Math.max(end,index[schar[i] - 'a']);
if(i == end){
res.add(end - start + 1);
start = end + 1;
}
}
return res;
}
}
时间复杂度:O(n);










