1 public class Solution { 2 public int lengthOfLongestSubstringKDistinct(String s, int k) { 3 if (k == 0) { 4 return 0; 5 } 6 7 Mapletters = new HashMap<>(); 8 int result = 0; 9 int count = 0;10 for (int left = 0, right = 0; right < s.length(); right++) {11 letters.put(s.charAt(right), letters.getOrDefault(s.charAt(right), 0) + 1);12 if (letters.get(s.charAt(right)) == 1) {13 count++;14 }15 16 if (count > k) {17 while (left < right && letters.get(s.charAt(left)) > 0) {18 int current = letters.get(s.charAt(left));19 letters.put(s.charAt(left++), current - 1);20 if (current == 1) {21 count--;22 break;23 }24 }25 }26 27 result = Math.max(result, right - left + 1);28 }29 return result;30 }31 }
1. put element do not forget to + 1
2. do not forget left move left++.