Leetcode 159 Solution

This article provides solution to leetcode question 159 (longest-substring-with-at-most-two-distinct-characters)

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; } };