AC java solution using LinkedHashMap


  • 0
    M
    public int lengthOfLongestSubstringKDistinct(String s, int k) {
        LinkedHashMap<Character, Integer> map = new LinkedHashMap<>(16, 0.75f, true);
        char[] array = s.toCharArray();
        int max = 0;
        int cur = 0;
        for(int i = 0; i < array.length; i++){
                map.put(array[i], i);
                cur ++;
                if(map.size() > k){
                    char keyToDelete = map.keySet().iterator().next();
                    int index = map.get(keyToDelete);
                    cur = i - index;
                    map.remove(keyToDelete);
                }
                max = Math.max(max, cur);
                
        }
        return max;
    
    }

Log in to reply
 

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