forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaximum-length-substring-with-two-occurrences.cpp
48 lines (44 loc) · 1.21 KB
/
maximum-length-substring-with-two-occurrences.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
// Time: O(n + 26)
// Space: O(26)
// freq table, sliding window, two pointers
class Solution {
public:
int maximumLengthSubstring(string s) {
static const int COUNT = 2;
int result = 0;
vector<int> cnt(26);
int right = 0, left = 0;
for (int invalid_cnt = 0; right < size(s); ++right) {
if (cnt[s[right] - 'a'] == COUNT) {
++invalid_cnt;
}
++cnt[s[right] - 'a'];
if (invalid_cnt) {
--cnt[s[left] - 'a'];
if (cnt[s[left++] - 'a'] == COUNT) {
--invalid_cnt;
}
}
}
return right - left;
}
};
// Time: O(n + 26)
// Space: O(26)
// freq table, sliding window, two pointers
class Solution2 {
public:
int maximumLengthSubstring(string s) {
static const int COUNT = 2;
int result = 0;
vector<int> cnt(26);
for (int right = 0, left = 0; right < size(s); ++right) {
++cnt[s[right] - 'a'];
while (cnt[s[right] - 'a'] > COUNT) {
--cnt[s[left++] - 'a'];
}
result = max(result, right - left + 1);
}
return result;
}
};