LeetCode763-划分字母区间

题目链接

英文链接:https://leetcode.com/problems/partition-labels/

中文链接:https://leetcode-cn.com/problems/partition-labels/

题目详述

字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一个字母只会出现在其中的一个片段。返回一个表示每个字符串片段的长度的列表。

示例 1:

1
2
3
4
5
6
输入: S = "ababcbacadefegdehijhklij"
输出: [9,7,8]
解释:
划分结果为 "ababcbaca", "defegde", "hijhklij"。
每个字母最多出现在一个片段中。
像 "ababcbacadefegde", "hijhklij" 的划分是错误的,因为划分的片段数较少。

注意:

  1. S的长度在[1, 500]之间。
  2. S只包含小写字母'a''z'

题目详解

贪心算法。

  • 首先构建一个数组记录每个字符最后一次出现的位置。
  • 用 end 来标记当前片段的结束位置。
  • 遍历数组,并维护 end,如果此时下标刚好等于 end,说明这个片段到此为止结束。
  • 为了统计每个片段的长度,还需要添加一个 start 标记当前片段的起始位置。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class LeetCode_00763 {

public List<Integer> partitionLabels(String S) {
char[] cs = S.toCharArray();
// 字符最后一次出现的位置
int[] last = new int[26];
for (int i = 0; i < cs.length; ++i) {
last[cs[i] - 'a'] = i;
}
List<Integer> res = new ArrayList<>();
int start = 0; // 片段起始位置
int end = 0; // 片段结束位置
for (int i = 0; i < cs.length; ++i) {
end = Math.max(end, last[cs[i] - 'a']);
if (i == end) {
res.add(end - start + 1);
start = i + 1;
}
}
return res;
}
}