Fork me on GitHub

longest-substring-with-at-most-two-distinct-characters

Description

https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
int lengthOfLongestSubstringTwoDistinct(string s) {
int maxLens = 0;
int curLens = 0;
unordered_map<char, int> counter;
int preIndex = 0;
for (int i = 0; i < s.size(); ++i) {
counter[s[i]] += 1;
while (counter.size() > 2) {
counter[s[preIndex]] -= 1;
if (counter[s[preIndex]] == 0) counter.erase(s[preIndex]);
preIndex += 1;
curLens -= 1;
}
curLens += 1;
maxLens = max(maxLens, curLens);
}
return maxLens;
}
};