Medium
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.
刷到谷歌面经“http://practice.geeksforgeeks.org/problems/longest-k-unique-characters-substring/0”这道题时发现的类似题,几乎就是一模一样,唯一的区别是这里多了个at most.也就是当s.length() < k时,返回的不是-1而是s.length().
class Solution {
public int lengthOfLongestSubstringKDistinct(String s, int k) {
if (s == null || s.length() == 0 || s.length() < k){
return s.length();
}
char[] chars = s.toCharArray();
Map<Character, Integer> map = new HashMap<>();
int start = 0;
int end = 0;
int maxLen = 0;
for (; end < chars.length; end++){
map.put(chars[end], map.getOrDefault(chars[end], 0) + 1);
while (map.size() > k){
char c = chars[start];
map.put(c, map.get(c) - 1);
if (map.get(c) == 0){
map.remove(c);
}
start++;
}
maxLen = Math.max(maxLen, end - start + 1);
}
return maxLen;
}
}