Easy to understand Java sliding window solution


  • 0
    public int lengthOfLongestSubstringKDistinct(String s, int k) {
        Map<Character, Integer> map = new HashMap<>();
        int lo=0;
        int hi=0;
        while(hi<s.length()) {
            map.put(s.charAt(hi), map.getOrDefault(s.charAt(hi),0)+1);
            if(map.size()>k) { // need to slide
                if(map.get(s.charAt(lo))==1)
                    map.remove(s.charAt(lo));
                else
                    map.put(s.charAt(lo), map.get(s.charAt(lo))-1);
                lo++;
                hi++;
            } else {
                hi++;
            }
        }
        return hi-lo;
    }

Log in to reply
 

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