Created
September 11, 2020 11:52
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode 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