Java Solution


  • 0
    V
    class Solution {
        public int lengthOfLongestSubstringKDistinct(String s, int k) {
            if (k <= 0) return 0;
            
            char[] A = s.toCharArray();
            int[] m = new int[256];
            int left = 0, right = 0, maxLen = 0, count = 0;
            while(right < A.length) {
                int index = (int)A[right];
                if(m[index] == 0) {
                    if (count++ == k) {
                        while(left < right && count > k) {
                            int val = (int)A[left];
                            m[val]--;
                            if (m[val] == 0) {
                                count--;
                            }
                            left++;
                        }
                    }
                }
                
                m[index]++;
                maxLen = Math.max(maxLen, right - left + 1);
                right++;
            }
            
            return maxLen;
        }
    }
    

Log in to reply
 

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