Given a string s
and an integer k
, return the length of the longest
s
that contains at most k
distinct characters.
Example 1:
Input: s = "eceba", k = 2 Output: 3 Explanation: The substring is "ece" with length 3.
Example 2:
Input: s = "aa", k = 1 Output: 2 Explanation: The substring is "aa" with length 2.
public int lengthOfLongestSubstringKDistinct(String s, int k) { Map<Character, Integer> map = new HashMap<>(); int left = 0; int best = 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); if (map.containsKey(leftChar)) { map.put(leftChar, map.get(leftChar) - 1); if (map.get(leftChar) == 0) { map.remove(leftChar); } } left++; } best = Math.max(best, i - left + 1); } return best; }
标签:map,Most,Distinct,leftChar,Substring,int,length,best,left From: https://www.cnblogs.com/immiao0319/p/16882582.html