@@ -0,0 +1,1545 @@
+/**%0A * Given a string, find the length of the longest substring T that contains at most k distinct characters. %0A * For example, given s = %22ecceba%22 and k = 2,%0A * T is %22ece%22 which has a length of 3 and 2 distinct characters.%0A */%0Apublic class Solution %7B%0A  public int lengthOfLongestSubstringKDistinct(String s, int k) %7B%0A    if (s.length() == 0 %7C%7C (s.length() == 1 && k == 1)) return s.length();%0A    if (s.length() == 1 && k %3E 1) return 0;%0A%0A    int i = 0; %0A    int j = 1;%0A    HashMap%3CCharacter, Integer%3E map = new HashMap%3CCharacter, Integer%3E();%0A    int distinct = s.charAt(i) == s.charAt(j) ? 1 : 2;%0A    int maxLength = 0;%0A    map.put(s.charAt(i), 1);%0A    map.put(s.charAt(j), distinct);%0A%0A    while (i %3C j && j %3C s.length() - 1) %7B%0A      char next = s.charAt(j + 1);%0A      // The number of distinct character is equal to K so we must remove the first distinct characters from the front.%0A      // Also update the max length.%0A      if (distinct %3E k) %7B%0A        char start = s.charAt(i);%0A        while (i %3C s.length() && start == s.charAt(i)) %7B %0A          // System.out.println(%22moving i: %22 + i);%0A          i ++;%0A          map.put(start, Math.max(0, map.containsKey(start) ? map.get(start) - 1 : 0));%0A        %7D%0A%0A        distinct --;%0A      %7D else %7B%0A        maxLength = Math.max(maxLength, j - i + 1);%0A      %7D%0A%0A      int count = map.containsKey(next) ? map.get(next) : 0;%0A      distinct = count != 0 ? distinct : distinct + 1; %0A      map.put(next, count + 1);%0A      j ++;%0A    %7D%0A%0A    return distinct %3E k ? maxLength : Math.max(maxLength, j - i + 1);%0A  %7D %0A%7D%0A

Add leetcode 340