340. Longest Substring with At Most K Distinct Characters

Given a string, find the length of the longest substring T that contains at most k distinct characters.

For example, Given s = “eceba” and k = 2,

T is "ece" which its length is 3.

Solution

public class Solution {
    public int lengthOfLongestSubstringKDistinct(String s, int k) {
        int count[] = new int[130];
        int left = 0, right = 0, maxLen = 0, cnt = 0;
        while(right < s.length()) {
            if(count[s.charAt(right++)]++ == 0) cnt++;
            while(cnt > k) if(--count[s.charAt(left++)] == 0) cnt--;
            maxLen = Integer.max(maxLen, right - left);
        }
        return maxLen;
    }
}

results matching ""

    No results matching ""