0% completed
Hi, For "Longest Substring with K Distinct Characters" question, curious to kno...
Sukumar
Jun 30, 2022
Hi, For "Longest Substring with K Distinct Characters" question, curious to know why map is used? also below solution with set is correct? please clarify. Thanks
static int findLongestSubString(String input, int K) { if (input == null || input.length() == 0 || input.length() < K) throw new IllegalArgumentException(); int maxCount = Integer.MIN_VALUE; int windowStart = 0; Set store = new HashSet(); for(int i = 0; i < input.length(); i++) { Character currentChar = input.charAt(i); store.add(currentChar); while(store.size() > K) { store.remove(input.charAt(windowStart)); windowStart++; } maxCount = Math.max(maxCount, (i - windowStart) + 1); } return (maxCount == Integer.MIN_VALUE) ? 0 : maxCount; }
0
0
Comments
Kiriyama Rei3 years ago
hello, we use a hashmap to keep count of the character frequency in our current window, for example if our window has "araa" then it has 3 "a" and 1 "r". So when we add another character to our window "araac" we have now 3 distinct characters (in the example we want onl...
Sukumar 3 years ago
Thanks for your response, so for this given problem is keeping count needed? as you can see my solution with set is also seems working so not sure what I am missing here.
On this page