-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathselect-k-disjoint-special-substrings.cpp
96 lines (92 loc) · 3.13 KB
/
select-k-disjoint-special-substrings.cpp
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// Time: O(n + 26^3)
// Space: O(26)
// hash table, sort, greedy
class Solution {
public:
bool maxSubstringLength(string s, int k) {
const auto& erase_overlap_intervals = [](auto& intervals) {
sort(begin(intervals), end(intervals), [](const auto& a, const auto& b) { return a[1] < b[1]; });
int result = 0, right = numeric_limits<int>::min();
for (const auto& x : intervals) {
if (x[0] <= right) {
++result;
} else {
right = x[1];
}
}
return result;
};
vector<int> cnt(26), lookup1(26, -1), lookup2(26, -1);
for (int i = 0; i < size(s); ++i) {
++cnt[s[i] - 'a'];
if (lookup1[s[i] - 'a'] == -1) {
lookup1[s[i] - 'a'] = i;
}
lookup2[s[i] - 'a'] = i;
}
vector<vector<int>> intervals;
for (const auto& i : lookup1) {
if (i == -1) {
continue;
}
for (const auto& j : lookup2) {
if (j == -1 || i > j) {
continue;
}
int total = 0;
for (int c = 0; c < size(cnt); ++c) {
if (i <= lookup1[c] && lookup1[c] <= lookup2[c] && lookup2[c] <= j) {
total += cnt[c];
}
}
if (total == j - i + 1 && total < size(s)) {
intervals.emplace_back(vector<int>{i, j});
}
}
}
return size(intervals) - erase_overlap_intervals(intervals) >= k;
}
};
// Time: O(26 * n + 26 * log(26))
// Space: O(26)
// hash table, sort, greedy
class Solution2 {
public:
bool maxSubstringLength(string s, int k) {
const auto& erase_overlap_intervals = [](auto& intervals) {
sort(begin(intervals), end(intervals), [](const auto& a, const auto& b) { return a[1] < b[1]; });
int result = 0, right = numeric_limits<int>::min();
for (const auto& x : intervals) {
if (x[0] <= right) {
++result;
} else {
right = x[1];
}
}
return result;
};
vector<char> cnt(26);
vector<int> lookup1(26, -1), lookup2(26, -1);
for (int i = 0; i < size(s); ++i) {
++cnt[s[i] - 'a'];
if (lookup1[s[i] - 'a'] == -1) {
lookup1[s[i] - 'a'] = i;
}
lookup2[s[i] - 'a'] = i;
}
vector<vector<int>> intervals;
for (int i = 0; i < size(s); ++i) {
if (i != lookup1[s[i] - 'a']) {
continue;
}
int x = i + 1, j = lookup2[s[i] - 'a'];
for (; x <= j && lookup1[s[x] - 'a'] >= i; ++x) {
j = max(j, lookup2[s[x] - 'a']);
}
if (x == j + 1 && (i != 0 || j != size(s) - 1)) {
intervals.emplace_back(vector<int>{i, j});
}
}
return size(intervals) - erase_overlap_intervals(intervals) >= k;
}
};