友情支持
如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜
有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。
公众号的微信号是: jikerizhi 。因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。 |
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 <= s.length <= 500
-
s
仅由小写英文字母组成
思路分析
本质来说,就是一个区间合并,把有重叠的区间全部合并成一个大区间即可。


-
一刷
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
27
28
29
30
31
32
33
34
35
36
/**
* @author D瓜哥 · https://www.diguage.com
* @since 2025-10-11 16:05:09
*/
public List<Integer> partitionLabels(String s) {
char[] charArray = s.toCharArray();
List<int[]> chars = new ArrayList<>(26);
for (int i = 0; i < 26; i++) {
chars.add(null);
}
List<int[]> charList = new ArrayList<>();
for (int i = 0; i < charArray.length; i++) {
int idx = charArray[i] - 'a';
int[] index = chars.get(idx);
if (Objects.isNull(index)) {
index = new int[2];
index[0] = i;
chars.set(idx, index);
charList.add(index);
}
index[1] = i;
}
List<int[]> result = new ArrayList<>();
result.add(charList.getFirst());
for (int i = 1; i < charList.size(); i++) {
int[] index = charList.get(i);
int[] last = result.getLast();
if (last[1] < index[0]) {
result.add(index);
} else {
last[1] = Math.max(last[1], index[1]);
}
}
return result.stream().map(i -> i[1] - i[0] + 1).toList();
}