难度:中等
字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一字母最多出现在一个片段中。返回一个表示每个字符串片段的长度的列表。
解题思路
- 先统计每个字符最后出现的位置;
- 然后标记当前片段最大结尾点,如果中间还有字符重复,并且在当前最大结尾点之后,则更新当前最大结尾点;
题解
public List<Integer> partitionLabels(String s) {
int length = s.length();
int[] lastCharIndex = new int[26];
for (int index = 0; index < length; index++) {
lastCharIndex[s.charAt(index) - 'a'] = index;
}
List<Integer> labelsSizeList = new ArrayList<>();
int start = 0;
int end = 0;
for (int index = 0; index < length; index++) {
end = Math.max(lastCharIndex[s.charAt(index) - 'a'], end);
if (index == end) {
labelsSizeList.add(end - start + 1);
start = end + 1;
}
}
return labelsSizeList;
}
测试
PartitionLabels partitionLabels = new PartitionLabels();
@Test
public void test_case1() {
Assertions.assertIterableEquals(Arrays.asList(9, 7, 8), partitionLabels.partitionLabels("ababcbacadefegdehijhklij"));
}
@Test
public void test_case2() {
Assertions.assertIterableEquals(Arrays.asList(1, 7, 1, 1, 2), partitionLabels.partitionLabels("abcdbcdcqwpp"));
}