Skip to content

Commit a637590

Browse files
authored
Update find-longest-self-contained-substring.cpp
1 parent b226568 commit a637590

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

C++/find-longest-self-contained-substring.cpp

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,3 +132,45 @@ class Solution3 {
132132
return result;
133133
}
134134
};
135+
136+
// Time: O(26^2 * n)
137+
// Space: O(26)
138+
// hash table, brute force
139+
class Solution5 {
140+
public:
141+
int maxSubstringLength(string s) {
142+
vector<int> left(26, -1), right(26, -1);
143+
for (int i = 0; i < size(s); ++i) {
144+
const int x = s[i] - 'a';
145+
if (left[x] == -1) {
146+
left[x] = i;
147+
}
148+
right[x] = i;
149+
}
150+
const auto& check = [&](int l, int r) {
151+
for (int i = l; i <= r; ++i) {
152+
const int x = s[i] - 'a';
153+
if (!(l <= left[x] && right[x] <= r)) {
154+
return false;
155+
}
156+
}
157+
return true;
158+
};
159+
160+
int result = -1;
161+
for (const auto& l : left) {
162+
if (l == -1) {
163+
continue;
164+
}
165+
for (const auto& r : right) {
166+
if (r == -1) {
167+
continue;
168+
}
169+
if (l <= r && result < r - l + 1 && r - l + 1 != size(s) && check(l, r)) {
170+
result = r - l + 1;
171+
}
172+
}
173+
}
174+
return result;
175+
}
176+
};

0 commit comments

Comments
 (0)