时间轴

2026-03-20

init


题目:

BFS 的做法:

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <vector>
#include <string>
#include <queue>

using std::vector;
using std::string;
using std::queue;

class Solution {
public:
vector<int> partitionLabels(string s)
{
// 1 <= s.length <= 500
// s 仅由小写英文字母组成
int i, n = s.size();
int start = 0;
vector<int> res;
vector<int> last_showed_pos(26, -1);

for (i = n - 1; i >= 0; i--) { // 每个字母最后一次出现的位置
if (last_showed_pos[s[i] - 'a'] == -1)
last_showed_pos[s[i] - 'a'] = i;
}

while (start < n) {
queue<char> que;
vector<bool> visited(26, false);
int len = 0;

que.push(s[start]);
visited[s[start] - 'a'] = true;

while (!que.empty()) {
char ch = que.front();
que.pop();

int boundary = last_showed_pos[ch - 'a'];

len = std::max(len, boundary - start + 1);

for (i = 0; i <= boundary; i++) {
if (!visited[s[i] - 'a']) {
que.push(s[i]);
visited[s[i] - 'a'] = true;
}
}
}
res.push_back(len);
start = start + len;
}
return res;
}
};