-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path159*.cpp
51 lines (45 loc) · 1.36 KB
/
159*.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
// 159. Longest Substring with At Most Two Distinct Characters - https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters
#include "bits/stdc++.h"
#include "gtest/gtest.h"
using namespace std;
class Solution {
public:
int lengthOfLongestSubstringTwoDistinct(string s) {
unordered_map<char, int> counts;
int k = 2;
int count = k;
int n = (int)s.length();
int L = 0, R = 0;
int result = 0;
while (R < n) {
char ch = s[R];
if (counts[ch]++ == 0) {
count -= 1;
}
// Works for k = 0, R < L:)
while (count < 0) {
if (counts[s[L++]]++ == 0) {
count += 1;
}
}
result = max(result, R - L + 1);
++R;
}
return result;
}
};
TEST(SolutionTest, Small) {
Solution sol;
EXPECT_EQ(3, sol.lengthOfLongestSubstringTwoDistinct("eceba"));
EXPECT_EQ(5, sol.lengthOfLongestSubstringTwoDistinct("aaaaa"));
EXPECT_EQ(2, sol.lengthOfLongestSubstringTwoDistinct("ab"));
}
TEST(SolutionTest, Empty) {
Solution sol;
EXPECT_EQ(0, sol.lengthOfLongestSubstringTwoDistinct(""));
}
int main(int argc, char **argv) {
ios::sync_with_stdio(false);
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}