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.

Example 1:

Input: s = "eceba", k = 2
Output: 3
Explanation: T is "ece" which its length is 3.

Example 2:

Input: s = "aa", k = 1
Output: 2
Explanation: T is "aa" which its length is 2.
int lengthOfLongestSubstringKDistinct(string s, int k) { // time: O(n); space: O(1)
    vector<int> record(128, 0);
    int begin = 0, end = 0, d = 0, counter = 0;
    while (end < s.length()) {
        if (record[s[end++]]++ == 0) {
            counter++;
        }
        while (counter > k) {
            if (record[s[begin++]]-- == 1) {
                counter--;
            }
        }
        d = max(d, end - begin);
    }
    return d;
}

Last updated

Was this helpful?