[LeetCode] Find Longest Self-Contained Substring

3104. Find Longest Self-Contained Substring

Given a string s, your task is to find the length of the longest self-contained substring of s.

A substring t of a string s is called self-contained if t != s and for every character in t, it doesn’t exist in the rest of s.

Return the length of the longest self-contained substring of s if it exists, otherwise, return -1.

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
class Solution {
public:
int maxSubstringLength(string s) {
int res = -1;
vector<pair<int, int>> best(26, {INT_MAX,INT_MIN});
vector<vector<int>> freq;
vector<int> f(26);
for(int i = 0; i < s.length(); i++) {
pair<int,int>& p = best[s[i]-'a'];
p.first = min(p.first, i);
p.second = i;
f[s[i]-'a']++;
freq.push_back(f);
}
auto query = [&](int l, int r) {
vector<int> res = freq[r];
if(l) {
for(int i = 0; i < 26; i++) res[i] -= freq[l-1][i];
}
return res;
};
vector<pair<int,int>> range;
for(int i = 0; i < 26; i++) {
if(best[i].first == INT_MAX) continue;
vector<int> vis(26);
queue<int> q;
int l = best[i].first, r = best[i].second;
auto push = [&](int x) {
if(!vis[x]) {
q.push(x);
vis[x] = true;
return true;
}
return false;
};
push(i);
while(q.size()) {
auto u = q.front(); q.pop();
auto [le,ri] = best[u];
l = min(l, le), r = max(r, ri);
vector<int> now = query(l,r);
for(int i = 0; i < 26; i++) if(now[i]) push(i);
}
if(l == 0 and r == s.length() - 1) continue;
res = max(res, r - l + 1);
range.push_back({l,r});
}
sort(begin(range), end(range));
for(int i = 0; i < range.size(); i++) {
int l = range[i].first, r = range[i].second;
for(int j = i + 1; j < range.size(); j++) {
if(r + 1 == range[j].first) {
r = range[j].second;
}
if(l == 0 and r == s.length() - 1) continue;
res = max(res, r - l + 1);
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/04/10/PS/LeetCode/find-longest-self-contained-substring/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.