159. Longest Substring with At Most Two Distinct Characters

Given a string s , find the length of the longest substring t that contains at most 2 distinct characters.

Example 1:

Input: "eceba"
Output: 3
Explanation: t is "ece" which its length is 3.

Example 2:

Input: "ccaabbb"
Output: 5
Explanation: t is "aabbb" which its length is 5.
int lengthOfLongestSubstringTwoDistinct(string s) { // 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 > 2) {
            if (record[s[begin++]]-- == 1) {
                counter--;
            }
        }
        d = max(d, end - begin);
    }
    return d;
}

Last updated

Was this helpful?