---
# System prepended metadata

title: 0159. Longest Substring with At Most Two Distinct Characters
tags: [Leetcode, Sliding Window, Medium]

---

# 0159. Longest Substring with At Most Two Distinct Characters
###### tags: `Leetcode` `Medium` `Sliding Window`
Link: https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/
## 思路
用map记录当前window里面每个字母的数量，如果map的数量大于2，说明有字母要拿走，挪动l，直到map的数量小于等于2
## Code
```java=
class Solution {
    public int lengthOfLongestSubstringTwoDistinct(String s) {
        Map<Character, Integer> map = new HashMap<>();
        int l=0, r=0, ans=0;
        while(r<s.length()){
            map.put(s.charAt(r), map.getOrDefault(s.charAt(r), 0)+1);
            while(map.size()>2){
                map.put(s.charAt(l), map.get(s.charAt(l))-1);
                if(map.get(s.charAt(l))==0){
                    map.remove(s.charAt(l));
                }
                l++;
            }
            ans = Math.max(ans, r-l+1);
            r++;
        }
        return ans;
    }
}
```