字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一个字母只会出现在其中的一个片段。返回一个表示每个字符串片段的长度的列表
输入:S = "ababcbacadefegdehijhklij"
输出:[9,7,8]
解释:
划分结果为 "ababcbaca", "defegde", "hijhklij"。
每个字母最多出现在一个片段中。
像 "ababcbacadefegde", "hijhklij" 的划分是错误的,因为划分的片段数较少。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/partition-labels
贪心,建立辅助数组用来记录字母最后一次出现的位置,记录出现过的字符在数组中下标最大值,当遍历的变量等于下标时,代表后面没有重复的字符了,可以划分成一个片段。
class Solution {
public List<Integer> partitionLabels(String S) {
int len = S.length();
int[] tmp = new int[26];
List<Integer> list = new ArrayList<>();
for (int i = 0; i < len; i++)
{
tmp[S.charAt(i)-'a'] = i;
}
int start = 0;
int max = 0;
for (int i = 0; i < len; i++)
{
max = Math.max(max,tmp[S.charAt(i)-'a']);
if (i == max)
{
list.add(max - start + 1);
start = max + 1;
}
}
return list;
}
}