-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.cpp
More file actions
78 lines (71 loc) · 1.57 KB
/
solution.cpp
File metadata and controls
78 lines (71 loc) · 1.57 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
//
// Created by mingyi on 20.04.20.
//
#include <vector>
#include <string>
#include <unordered_map>
#include <cassert>
using namespace std;
vector<int> partitionLabels(string S) {
// // first solution slow
// unordered_map<char, int> ends;
// for (int i = 0; i < S.size(); i++) {
// ends[S[i]] = i;
// }
//
// vector<int> ans;
// int start = 0;
// int prev = 0;
// while (start < S.size()) {
// int end = ends[S[start]];
// while (start++ < end) {
// end = max(end, ends[S[start]]);
// }
// ans.push_back(start - prev);
// prev = start;
// }
// return ans;
// // second solution
// vector<int> ends(26, -1);
// for (int i = 0; i < S.size(); i++) {
// ends[S[i] - 'a'] = i;
// }
//
// vector<int> ans;
// int start = 0;
// int prev = 0;
// while (start < S.size()) {
// int end = ends[S[start] - 'a'];
// while (start++ < end) {
// end = max(end, ends[S[start] - 'a']);
// }
// ans.push_back(start - prev);
// prev = start;
// }
// return ans;
// third solution
vector<int> ends(26, -1);
for (int i = 0; i < S.length(); i++) {
ends[S[i] - 'a'] = i;
}
vector<int> ans;
int begin = 0, end = 0;
for (int i = 0; i < S.length(); i++) {
if (ends[S[i] - 'a'] > end) {
end = ends[S[i] - 'a'];
}
if (i == end) {
ans.push_back(end - begin + 1);
begin = i + 1;
}
}
return ans;
}
int main() {
string S = "ababcbacadefegdehijhklij";
vector<int> expect {9, 7, 8};
vector<int> result = partitionLabels(S);
for (int i = 0; i < result.size(); i++) {
assert(expect[i] == result[i]);
}
}