Skip to content

Instantly share code, notes, and snippets.

@khekrn
Created September 11, 2020 11:52
Show Gist options
  • Save khekrn/1480b4726b2358a9ed8308dd5b668947 to your computer and use it in GitHub Desktop.
Save khekrn/1480b4726b2358a9ed8308dd5b668947 to your computer and use it in GitHub Desktop.
find the length of the longest substring in it with no more than K distinct characters.
public class LongestSubStringWithKDistinctChar{
//O(N + K)
public int findLength(String str, int K) {
int windowStart = 0, maxLen = 0;
var dict = new HashMap<Character, Integer>();
for(int i = 0; i < str.length(); i++){
char rightChar = str.charAt(i);
dict.put(rightChar, dict.getOrDefault(rightChar, 0) + 1);
while(dict.size() > K){
char leftChar = str.charAt(windowStart);
dict.put(leftChar, dict.get(leftChar) - 1);
if(dict.get(leftChar) == 0){
dict.remove(leftChar);
}
windowStart++;
}
maxLen = Math.max(maxLen, (i-windowStart)+1);
}
return maxLen;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment