763. 划分字母区间
贪心:
java
class Solution {
public List<Integer> partitionLabels(String s) {
List<Integer> ans = new ArrayList<>();
int len = s.length();
char[] chars = s.toCharArray();
//记录每一个片段开始的下标
int end = 0;
int start = 0;
//用一个数组记录每一个字母出现的最晚下标
int[] last = new int[26];
for(int i = 0;i<len;i++){
last[chars[i] - 'a'] = i;
}
//遍历字符串,找片段
for(int j = 0;j<len;j++){
//记录当前片段的最近下标
end = Math.max(end,last[chars[j] - 'a']);
if(j == end){
ans.add(end-start+1);
start = end+1;
}
}
return ans;
}
}
时间复杂度:O(N)
空间复杂度:O(∣Σ∣),其中 Σ 是字符串中的字符集。这道题中,字符串只包含小写字母,因此 ∣Σ∣=26