
统计+贪心
解题思路:时间复杂度O(
n
n
n),空间复杂度O(
26
26
26),其中26是因为字符串s的字符范围是26个字母 |
---|
- 我们先统计每一个字符最后出现的位置。也就是字符a在字符串s中最右边的位置
- 然后遍历字符串s,每遍历一个字符,就获取这个字符a的最右侧位置。并统计这个最右侧的位置为curRight
- 如果当前字符a的位置并不是a这个字符在s中最右侧的位置aRight,那么当前位置无法划分为一个区间。
因为一个每个区间不能有交集,如果在当前位置划分区间,下一个区间必定会划分字符a。我们必须令当前区间将a完全包含
- 而目前这个区间最好的情况,也只能是到aRight正好划分一个区间,所以只能令curRight = aRight
- 如果当前字符a的aRight,正好和curRight一至,说明当前区间是一个和其它区间没有交集的区间,统计答案即可

class Solution {
public List<Integer> partitionLabels(String s) {
char[] strs = s.toCharArray();
int[] last = new int[26];
for(int i = 0; i < strs.length; i++) last[strs[i] - 'a'] = i;
int curRight = -1;
int curLeft = 0;
List<Integer> res = new ArrayList<>();
for(int i = 0; i < strs.length; i++){
int index = (int)(strs[i] - 'a');
if(last[index] > curRight) curRight = last[index];
if(i == curRight) {
res.add(curRight - curLeft + 1);
curLeft = curRight + 1;
}
}
return res;
}
}