Java Solution 5 ms


  • 0
    S
    public int lengthOfLongestSubstringKDistinct(String S, int k) {
        
            if(S==null)  return 0
            if(S.length()<k) return S.length();
    
    	int [] map = new int[256];
    	int maxLen=k;
    	int start=0;
    	char [] array = S.toCharArray();
    	int left=0;
    	int uCount=0; // stores # unique characters
    	 
    	for(int i=0;i<array.length;i++){
    
    		char c = array[i];
    		if(map[c]==0) uCount++;
    		map[c]++;
    
    		if(uCount>k) { 
    			maxLen = Math.max(maxLen, (i-start));				
    			while(uCount>k){
    				char fc = array[start];
    				if(map[fc]==1) uCount--;
    				map[fc]--;
     				start++;
    			}
    		}
    	}
    
    	maxLen = Math.max(maxLen, (array.length-start));
    	return maxLen;
    }

Log in to reply
 

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