Java solution using sliding window with hashmap


  • 0
    J
    class Solution {
        public int lengthOfLongestSubstringKDistinct(String s, int k) {
            
            int start = 0, end = 0, maxLen = 0;
            Map<Character, List<Integer>> map = new HashMap<>();
            
            while(end < s.length()) {  
                char e = s.charAt(end);
                if(!map.containsKey(e)) map.put(e, new ArrayList<Integer>());
                map.get(e).add(end);
                while(start <= end && map.keySet().size() > k) {
                    char c = s.charAt(start);
                    map.get(c).remove(new Integer(start));
                    if(map.get(c).size() == 0) map.remove(c);
                    start ++;
                }
                maxLen = Math.max(maxLen, end - start + 1);
                end ++;
            }
            return maxLen;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.