> For the complete documentation index, see [llms.txt](https://protegejj.gitbook.io/algorithm-practice/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://protegejj.gitbook.io/algorithm-practice/leetcode/two-pointers/159-longest-substring-with-at-most-two-distinct-characters.md).

# 159 Longest Substring with At Most Two Distinct Characters

## 159. [Longest Substring with At Most Two Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/description/)

## 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**

```java
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)
