Find the longest substring with exactly two distinct characters?
public int LengthOfLongestSubstringTwoDistinct(string s) {
int left = 0, right = 0, maxLen = 0;
Dictionary<char, int> map = new Dictionary<char, int>();
while (right < s.Length) {
Follow on:
char c = s[right];
map[c] = right;
if (map.Count > 2) {
int delIndex = map.Values.Min();
map.Remove(s[delIndex]);
left = delIndex + 1;
maxLen = Math.Max(maxLen, right - left + 1);
right++;
return maxLen;
Explanation:
Sliding window with hashmap to track indices of distinct chars, remove the leftmost when
>2.