Skip to content

Commit a919f54

Browse files
authored
Create 3458.Select-K-Disjoint-Special-Substrings.cpp
1 parent 72289e7 commit a919f54

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
class Solution {
2+
public:
3+
bool maxSubstringLength(string s, int k)
4+
{
5+
int n = s.size();
6+
vector<vector<int>>pos(26);
7+
for (int i=0; i<n; i++)
8+
pos[s[i]-'a'].push_back(i);
9+
10+
vector<pair<int, int>>intervals;
11+
for (int letter=0; letter<26; letter++)
12+
{
13+
if (pos[letter].empty()) continue;
14+
int start = pos[letter][0];
15+
int i = start;
16+
int far = pos[letter].back();
17+
18+
bool flag = true;
19+
while (i<=far)
20+
{
21+
far = max(far, pos[s[i]-'a'].back());
22+
if (pos[s[i]-'a'][0]<start)
23+
{
24+
flag = false;
25+
break;
26+
}
27+
i++;
28+
}
29+
if (far-start+1==n) continue;
30+
if (flag==false) continue;
31+
intervals.push_back({start, far});
32+
}
33+
34+
return helper(intervals)>=k;
35+
}
36+
37+
38+
int helper(vector<pair<int, int>> &intervals) {
39+
sort(intervals.begin(), intervals.end(), [](pair<int, int> a, pair<int, int> b) {
40+
return a.second < b.second;
41+
});
42+
43+
int count = 0;
44+
int far = INT_MIN;
45+
46+
for (auto &interval : intervals)
47+
{
48+
if (interval.first > far) {
49+
count++;
50+
far = interval.second;
51+
}
52+
}
53+
return count;
54+
}
55+
};

0 commit comments

Comments
 (0)