> For the complete documentation index, see [llms.txt](https://anand-aryan.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://anand-aryan.gitbook.io/leetcode/159.-longest-substring-with-at-most-two-distinct-characters.md).

# 159. Longest Substring with At Most Two Distinct Characters

Longest Substring with At Most Two Distinct Characters

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.

## Solution <a href="#solution" id="solution"></a>

```java
public class Solution {
     public int lengthOfLongestSubstringTwoDistinct(String s) {
        if (s == null || s.length() == 0) return 0;

        int result = Integer.MIN_VALUE;
        Map<Character, Integer> map = new HashMap<>();
        int startIndex = 0;
        int endIndex = 0;

        while (endIndex < s.length()) {
            Character currentChar = s.charAt(endIndex);
            map.merge(currentChar, 1, (a, b) -> a + b);
            if (map.size() <= 2) {
                result = Math.max(result, endIndex - startIndex + 1);
            } else {
                // move startIndex
                while (map.size() > 2) {
                    Character removeChar = s.charAt(startIndex);
                    map.merge(removeChar, 1, (a,b)->a-b);
                    if (map.get(removeChar) == 0) {
                        map.remove(removeChar);
                    }

                    startIndex ++;
                }
            }

            endIndex ++;
        }

        return result;
    }
}
```
