把上题的2换成k即可
public int lengthOfLongestSubstringKDistinct(String s, int k) { if (s == null || s.length() == 0 || k == 0) { return 0; } char[] sArr = s.toCharArray(); int[] hash = new int[256]; int l = 0, count = 0, result = 1; for (int r = 0; r < sArr.length; ++r) { hash[sArr[r]]++; if (hash[sArr[r]] == 1) { count++; } while (count > k) { hash[sArr[l]]--; if (hash[sArr[l]] == 0) { count--; } l++; } result = Math.max(result, r - l + 1); } return result; }