字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一个字母只会出现在其中的一个片段。返回一个表示每个字符串片段的长度的列表。
示例 1:
输入: S = “ababcbacadefegdehijhklij”
输出: [9,7,8]
解释:
划分结果为 “ababcbaca”, “defegde”, “hijhklij”。
每个字母最多出现在一个片段中。
像 “ababcbacadefegde”, “hijhklij” 的划分是错误的,因为划分的片段数较少。
思路:
1.使用一个数组存储每个字母最后出现的位置
2.从头开始查找这样的 “字符串” ,对应字符串中的每个字母,它出现的最后的那个字母已经包含在整个字符串中。
3.答案需要返回每一个截取的长度,所以需要记录start的位置和end的位置。
public List<Integer> partitionLabels(String S) {
if (S == null || S.length() == 0) {
return new ArrayList<Integer>();
}
List<Integer> list = new ArrayList<Integer>();
int start = 0;
int end = 0;
int[] index = new int[26];
char[] arr = S.toCharArray();
for (int i = 0; i < arr.length; i++) {
index[arr[i] - 'a'] = i;
}
end = index[arr[0] - 'a'];
for (int i = start; i < arr.length; i++) {
end = Math.max(index[arr[i] - 'a'], end);
if (i == end) {
list.add(end - start + 1);
start = end + 1;
}
}
return list;
}