@@ -0,0 +1,1409 @@
+package advanced.scan.twopointers.lc159_longestsubstringwithatmosttwodistinctcharacters;%0A%0Aimport org.junit.jupiter.api.Assertions;%0Aimport org.junit.jupiter.api.Test;%0A%0Aimport java.util.HashMap;%0Aimport java.util.Map;%0A%0A/**%0A * Given a string S, find the length of the longest substring T that contains at most two distinct characters.%0A */%0Apublic class Solution %7B%0A%0A    @Test%0A    void test() %7B%0A        Assertions.assertEquals(0, lengthOfLongestSubstring(%22%22));%0A        Assertions.assertEquals(1, lengthOfLongestSubstring(%22a%22));%0A        Assertions.assertEquals(2, lengthOfLongestSubstring(%22aa%22));%0A        Assertions.assertEquals(3, lengthOfLongestSubstring(%22aba%22));%0A        Assertions.assertEquals(4, lengthOfLongestSubstring(%22abab%22));%0A        Assertions.assertEquals(2, lengthOfLongestSubstring(%22abcda%22));%0A        Assertions.assertEquals(3, lengthOfLongestSubstring(%22eceba%22));%0A    %7D%0A%0A    public int lengthOfLongestSubstring(String s) %7B%0A        Map%3CCharacter, Integer%3E win = new HashMap%3C%3E();%0A        int max = 0, len = 0;%0A        for (int i = 0; i %3C s.length(); i++) %7B%0A            char r = s.charAt(i);%0A            win.put(r, win.getOrDefault(r, 0) + 1);%0A            for (int j = i - len; win.size() %3E 2; j++, len--) %7B%0A                char l = s.charAt(j);%0A                if (!win.remove(l, 1)) win.put(l, win.get(l) - 1);%0A            %7D%0A            max = Math.max(max, ++len);%0A        %7D%0A        return max;%0A    %7D%0A%0A%7D%0A

longest substring with at most distinct characters