Why use the hashmap with for and while loops, when you can use a hashset with if/else inside the for loop?
class LongestSubstringKDistinct {
public static int findLength(String str, int k) {
Set<Character> l = new HashSet<Character>();
int start = 0;
int max = 0;
char[] chars = str.toCharArray();
for(int end = 0; end < chars.length; end++) {
l.add(chars[end]);
if(l.size() <= k) {
max = Math.max(max, end - start +1);
} else {
l.remove(chars[start]);
start++;
}
}
return max;
}
}