class Solution {
public int lengthOfLongestSubstringKDistinct(String s, int k) {
if (s == null || s.length() == 0 || k == 0) {
return 0;
}
HashMap<Character, Integer> count = new HashMap<>();
int n = s.length();
int firstIdx = 0;
char[] chs = s.toCharArray();
int longest = 0;
for (int i = 0; i < n; i++) {
count.put(chs[i], count.getOrDefault(chs[i], 0) + 1);
while (count.size() > k) {
count.put(chs[firstIdx], count.get(chs[firstIdx]) - 1);
if (count.get(chs[firstIdx]) == 0) {
count.remove(chs[firstIdx]);
}
firstIdx++;
}
longest = Math.max(longest, i - firstIdx + 1);
}
return longest;
}
}