Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- class LongestSubstringKDistinct {
- public static int findLength(String str, int k) {
- // TODO: Write your code here
- // map to store count.
- Map<Character, Integer> map = new HashMap<>();
- int maxLength = 0;
- int windowStart = 0;
- for(int windowEnd = 0; windowEnd < str.length(); windowEnd++) {
- char rightChar = str.charAt(windowEnd);
- // store character count in map
- map.put(rightChar, map.getOrDefault(rightChar, 0)+1);
- // compare mapsize with k and loop till mapsize less than or equal to k
- while(map.size() > k) {
- // shrink by examining right character.
- char leftChar = str.charAt(windowStart);
- // reduce leftChar len and remove if len is 0
- map.put(leftChar, map.get(leftChar)-1);
- if(map.get(leftChar) == 0) {
- map.remove(leftChar);
- }
- // slide to right.
- windowStart++;
- }
- maxLength = Math.max(maxLength, windowEnd-windowStart + 1);
- }
- return maxLength;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement