Sliding Window Solution (Java)


  • 2
    B
    public int lengthOfLongestSubstringKDistinct(String s, int k) {
        if(null == s || k <=0 )
            return 0;
    
        int len = s.length();
        if(len <= 1)
            return len;
    
        int h=0, l=0, max =0;
        HashMap<Character, Integer> map = new HashMap<>();
    
        while(h < len){
            if(map.size() <= k){
                map.put(s.charAt(h), h);
            }
    
            if(map.size() > k){
                int leftmost = Integer.MAX_VALUE;
                for(int n : map.values()){
                    leftmost = Math.min(leftmost, n);
                }
                
                l = leftmost + 1;
                map.remove(s.charAt(leftmost));
            }
            
            max = Math.max(max, h - l + 1);
            h++;
        }
        
        return max;        
    }

Log in to reply
 

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