Leetcode 763.划分字母区间

题目要求

  • 给你一个字符串 s 。我们要把这个字符串划分为尽可能多的片段,同一字母最多出现在一个片段中。例如,字符串 “ababcc” 能够被分为 [“abab”, “cc”],但类似 [“aba”, “bcc”] 或 [“ab”, “ab”, “cc”] 的划分是非法的。

  • 注意,划分结果需要满足:将所有划分结果按顺序连接,得到的字符串仍然是 s 。

  • 返回一个表示每个字符串片段的长度的列表。

示例 1:
输入:s = “ababcbacadefegdehijhklij”
输出:[9,7,8]
解释:
划分结果为 “ababcbaca”、“defegde”、“hijhklij” 。
每个字母最多出现在一个片段中。
像 “ababcbacadefegde”, “hijhklij” 这样的划分是错误的,因为划分的片段数较少。

示例 2:
输入:s = “eccbbbbdec”
输出:[10]

贪心

思路:
统计每一个字符最后出现的位置
从头遍历字符,并更新字符的最远出现下标,如果找到字符最远出现位置下标和当前下标相等了,则找到了分割点

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public List<Integer> partitionLabels(String s) {
List<Integer> list = new LinkedList<>();
int[] index = new int[26];
// 统计每个字符最后出现的位置
for (int i = 0; i < s.length(); i++) {
index[s.charAt(i) - 'a'] = i;
}
// 与s中对应每个字符的最远出现位置
int[] count = new int[s.length()];
for (int i = 0; i < count.length; i++) {
count[i] = index[s.charAt(i) - 'a'];
}
int idx = 0;
int last = -1;
for (int i = 0; i < s.length(); i++) {
idx = Math.max(idx,count[i]);
// 找到分割点
if (i == idx) {
list.add(i - last);
last = i;
}
}
return list;
}
}