划分字母区间
约 370 字大约 1 分钟
划分字母区间
题目描述
给你一个字符串 s 。我们要把这个字符串划分为尽可能多的片段,同一字母最多出现在一个片段中。
注意,划分结果需要满足:将所有划分结果按顺序连接,得到的字符串仍然是 s 。
返回一个表示每个字符串片段的长度的列表。
示例
输入:s = "ababcbacadefegdehijhklij"
输出:[9,7,8]
解释:
划分结果为 "ababcbaca", "defegde", "hijhklij"。
每个字母最多出现在一个片段中。
像 "ababcbacadefegde", "hijhklij" 这样的划分是错误的,因为划分的片段数较少。
输入:s = "eccbbbbdec"
输出:[10]解析
贪心算法:
- 将字符串转换成字符数组,初始化容量为26的数组存储相同字母最后出现的下标
- 记录 start、end位置,遍历数组每次更新当前元素最后一次出现的最远距离
- 若当前元素出现的最远距离为当前下标,进行数组风分割记录当前位置,更新start
代码
class Solution {
public List<Integer> partitionLabels(String s) {
char[] arr = s.toCharArray();
int[] indexLast = new int[26];
for (int i = 0; i < arr.length; i++) {
indexLast[arr[i] - 'a'] = i;
}
int start = 0, end = 0;
List<Integer> res = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
end = Math.max(end, indexLast[arr[i] - 'a']);
if (i == end) {
res.add(end - start + 1);
start = i + 1;
}
}
return res;
}
}