Given a string, find the length of the longest substring T that contains at most 2 distinct characters.
For example, Given s = “eceba”
,
T is "ece" which its length is 3.
1 public class Solution { 2 public int LengthOfLongestSubstringTwoDistinct(string s) { 3 if (s == null) return 0; 4 if (s.Length < 2) return s.Length; 5 6 var dict = new Dictionary<char, int>(); 7 8 int i = 0, j = 0, max = 0; 9 10 while (j < s.Length) 11 { 12 dict[s[j]] = j; 13 14 if (dict.Count > 2) 15 { 16 char toDelete = ‘*‘; 17 var min = Int32.MaxValue; 18 19 foreach (var pair in dict) 20 { 21 if (pair.Value < min) 22 { 23 min = pair.Value; 24 toDelete = pair.Key; 25 } 26 } 27 28 i = min + 1; 29 dict.Remove(toDelete); 30 } 31 else 32 { 33 max = Math.Max(j - i + 1, max); 34 } 35 36 j++; 37 } 38 39 return max; 40 } 41 }