My java solution, using slide window.


  • 0
    public int lengthOfLongestSubstringKDistinct(String s, int k) {
        int left = 0, right = 0;
        int maxLen = Integer.MIN_VALUE;
        
        int counter = 0;
        
        int[] map = new int[256];
        
        while(right < s.length()){
            if(map[s.charAt(right)] == 0){
                counter ++;
            }
            map[s.charAt(right)] ++;
            right ++;
            
            while(counter > k){
                if(map[s.charAt(left)] == 1){
                    counter --;
                }
                map[s.charAt(left)] --;
                left ++;
            }
            
            maxLen = Math.max(right - left, maxLen);
        }
        
        return maxLen == Integer.MIN_VALUE ? 0 : maxLen;
    }

Log in to reply
 

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