159 Longest Substring with At Most Two Distinct Characters

1. Question

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

For example, Given s =“eceba”,

T is "ece" which its length is 3.

2. Implementation

(1) Two Pointer + Hash

class Solution {
    public int lengthOfLongestSubstringTwoDistinct(String s) {
        if (s.length() <= 2) {
            return s.length();
        }

        int maxLen = 0;
        int start = 0, end = 0, count = 0;
        int[] map = new int[256];

        while (end < s.length()) {
            if (map[s.charAt(end)] == 0) {
                ++count;
            }
            ++map[s.charAt(end)];
            ++end;

            while (count > 2) {
                if (map[s.charAt(start)] == 1) {
                    --count;
                }
                --map[s.charAt(start)];
                ++start;
            }

            maxLen = Math.max(maxLen, end - start);
        }
        return maxLen;
    }
}

3. Time & Space Complexity

Two Pointer + Hash: 时间复杂度O(n), 空间复杂度O(1)

Last updated