> For the complete documentation index, see [llms.txt](https://wentao-shao.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://wentao-shao.gitbook.io/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/>

## 题目描述

```
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.
```

## 代码

### Approach #1 Sliding Window + HashMap

```java
class Solution {
  public int lengthOfLongestSubstringTwoDistinct(String s) {
        int n = s.length;
    if (n < 3)    return n;

    int left = 0;
    int right = 0;

    HashMap<Character, Integer> hashmap = new HashMap<Character, Integer>();

    int max_len = 2;

    while (right < n) {
      if (hashmap.size() < 3) {
        hashmap.put(s.charAt(right), right++);
      }

      if (hashmap.size() == 3) {
        int del_idx = Collections.min(hashmap.values());
        hashmap.remove(s.charAt(del_idx));
        left = del_idx + 1;
      }

      max_len = Math.max(max_len, right - left);
    }

    return max_len;
  }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wentao-shao.gitbook.io/leetcode/two-pointers/159.longest-substring-with-at-most-two-distinct-characters.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
