Leetcode 159 Solution
This article provides solution to leetcode question 159 (longest-substring-with-at-most-two-distinct-characters)
Access this page by simply typing in "lcs 159" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters
Solution
class Solution {
public:
int lengthOfLongestSubstringTwoDistinct(string s) {
map<char, int> m;
int l = 0;
int max_len = 0;
for (int i = 0; i < s.size(); i++)
{
m[s[i]]++;
while (l <= i && m.size() > 2)
{
auto ch = s[l++];
m[ch]--;
if (m[ch] == 0)
m.erase(ch);
}
max_len = max(max_len, i - l + 1);
}
return max_len;
}
};