class Solution { public int lengthOfLongestSubstringKDistinct(String s, int k) { HashMap<Character, Integer> map = new HashMap<>(); int res = 0, left = 0; for (int i = 0; i < s.length(); ++i) { char c = s.charAt(i); map.put(c, map.getOrDefault(c, 0) + 1); while (map.size() > k) { char leftChar = s.charAt(left); map.put(leftChar, map.get(leftChar) - 1); if (map.get(leftChar) == 0) map.remove(leftChar); left++; } // update res res = Math.max(res, i - left + 1); } return res; } }