Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save binfeng/b494193322cc55c6d1b3a2b724e2883d to your computer and use it in GitHub Desktop.

Select an option

Save binfeng/b494193322cc55c6d1b3a2b724e2883d to your computer and use it in GitHub Desktop.
public class Solution {
/**
* @param s : A string
* @return : The length of the longest substring
* that contains at most k distinct characters.
*/
public int lengthOfLongestSubstringKDistinct(String s, int k) {
// write your code here
if(s == null || s.length() == 0 || k == 0){
return 0;
}
if(s.length() <= k){
return s.length();
}
HashMap<Character, Integer> map = new HashMap<>();
int left = 0;
int right = 0;
int max = 0;
while(right < s.length()){
//如果遇到的字符是之前出现过的,则直接将其数量加1
if(map.containsKey(s.charAt(right))){
map.put(s.charAt(right), map.get(s.charAt(right)) + 1);
}else{
//如果遇到的新字符之前没有出现过则分情况讨论
//若目前遇到过字符种类不足k个,则直接加入
if(map.size() < k){
map.put(s.charAt(right), 1);
}else{
//若目前遇到过的字符种类大于k个,则移动左边界减少字符,直到字符种类少于k个后再加入
max = Math.max(max, right - left);
while(map.size() >= k){
map.put(s.charAt(left), map.get(s.charAt(left)) - 1);
if(map.get(s.charAt(left)) == 0){
map.remove(s.charAt(left));
}
left++;
}
map.put(s.charAt(right), 1);
}
}
right++;
}
//right到底之后要统计最后一次substring的长度
max = Math.max(max, right - left);
return max;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment