问题分析
题目要求将字符串 s 划分为尽可能多的片段,每个片段中的字母不会出现在其他片段中,并返回这些片段的长度。
解题思路
步骤 1:记录每个字符的最后出现位置
• 先遍历字符串 s,用一个 last 数组(长度为 26,表示 a-z)存储 每个字符的最后出现位置。
• 这样在后续遍历时,就可以知道当前段落中的所有字符最远延伸到哪里。
步骤 2:遍历字符串并确定片段
• 使用 start 和 end 来维护当前片段的起始和结束索引:
• end 表示当前片段的最远边界(即当前片段中所有字符的最远出现位置)。
• 每遍历一个字符,都更新 end 为当前字符的最远出现位置。
• 如果 i == end,说明当前片段结束,记录该片段长度 end - start + 1,并更新 start 为 end + 1。
详细运行步骤
假设输入字符串:
s = "ababcbacadefegdehijhklij"
Step 1: 计算每个字符的最后出现位置
遍历 s,记录每个字符的最后出现索引:
a -> 8
b -> 5
c -> 7
d -> 14
e -> 15
f -> 11
g -> 13
h -> 19
i -> 22
j -> 23
k -> 20
l -> 21
last 数组会存成:
last = [8, 5, 7, 14, 15, 11, 13, 19, 22, 23, 20, 21, ...]
(只显示 s 中出现的字符)
Step 2: 遍历 s 进行分割
初始化 start = 0, end = 0,开始遍历:
Index i | s[i] | end 更新 | 说明 |
---|---|---|---|
0 | a | max(0, 8) = 8 | a 最远出现位置 8 |
1 | b | max(8, 5) = 8 | b 最远 5,不变 |
2 | a | max(8, 8) = 8 | a 最远 8,不变 |
3 | b | max(8, 5) = 8 | b 不变 |
4 | c | max(8, 7) = 8 | c 最远 7,不变 |
5 | b | max(8, 5) = 8 | b 不变 |
6 | a | max(8, 8) = 8 | a 不变 |
7 | c | max(8, 7) = 8 | c 不变 |
8 | a | i == end → 划分 [0,8] | 长度 8 - 0 + 1 = 9 |
第一段:“ababcbaca”(长度 9)
更新 start = 9,继续遍历:
Index i | s[i] | end 更新 | 说明 |
---|---|---|---|
9 | d | max(9, 14) = 14 | d 最远 14 |
10 | e | max(14, 15) = 15 | e 最远 15 |
11 | f | max(15, 11) = 15 | f 不变 |
12 | e | max(15, 15) = 15 | e 不变 |
13 | g | max(15, 13) = 15 | g 不变 |
14 | d | max(15, 14) = 15 | d 不变 |
15 | e | i == end → 划分 [9,15] | 长度 15 - 9 + 1 = 7 |
第二段:“defegde”(长度 7)
更新 start = 16,继续遍历:
Index i | s[i] | end 更新 | 说明 |
---|---|---|---|
16 | h | max(16, 19) = 19 | h 最远 19 |
17 | i | max(19, 22) = 22 | i 最远 22 |
18 | j | max(22, 23) = 23 | j 最远 23 |
19 | h | max(23, 19) = 23 | h 不变 |
20 | k | max(23, 20) = 23 | k 不变 |
21 | l | max(23, 21) = 23 | l 不变 |
22 | i | max(23, 22) = 23 | i 不变 |
23 | j | i == end → 划分 [16,23] | 长度 23 - 16 + 1 = 8 |
第三段:“hijhklij”(长度 8)
最终结果:
[9, 7, 8]
代码解析
class Solution {
public:
vector<int> partitionLabels(string s) {
int last[26]; // 记录每个字符的最后出现位置
int length = s.size();
// 1. 预处理:找到每个字母的最远出现位置
for (int i = 0; i < length; i++) {
last[s[i] - 'a'] = i;
}
vector<int> partition;
int start = 0, end = 0;
// 2. 遍历字符串,按规则划分
for (int i = 0; i < length; i++) {
end = max(end, last[s[i] - 'a']); // 更新 end 为当前字符的最远位置
if (i == end) { // 当 i 到达当前片段的最远位置时
partition.push_back(end - start + 1); // 记录片段长度
start = end + 1; // 更新新的片段起点
}
}
return partition;
}
};
时间复杂度分析
• Step 1: 计算 last 数组 → O(n)
• Step 2: 遍历 s 进行分割 → O(n)
• 总时间复杂度 = O(n)