Longest Substring with At Most K Distinct Characters
Given a string, find the length of the longest substring T that contains at most k distinct characters.
For example,
Given s = “eceba” and k = 2,
T is "ece" which its length is 3.
Solution
public class Solution {
public int lengthOfLongestSubstringKDistinct(String s, int k) {
if (s == null || s.length() == 0 || k <= 0) return 0;
Map<Character, Integer> map = new HashMap<>();
int left = 0;
int result = 0;
for (int i = 0; i < s.length(); i++) {
map.merge(s.charAt(i), 1, (a, b) -> a + b);
if (map.size() > k) {
while (map.size() > k) {
map.merge(s.charAt(left), 1, (a,b)->a-b);
if (map.get(s.charAt(left)) == 0) {
map.remove(s.charAt(left));
}
left++;
}
}
result = Math.max(result, i - left+1);
}
return result;
}
}