159. Longest Substring with At Most Two Distinct Characters 发表于 2022-02-08 Sliding Window123456789101112131415161718192021222324252627class Solution { public int lengthOfLongestSubstringTwoDistinct(String s) { int[] count = new int[128]; int i = 0, maxLength = 0, distinctCharCount = 0; for (int j = 0; j < s.length(); j++) { char c = s.charAt(j); // 不重复字符已经达到两个且 c 是一个新的字符 while (distinctCharCount == 2 && count[c] == 0) { char leftmost = s.charAt(i); if (--count[leftmost] == 0) { distinctCharCount--; } i++; } if (count[c]++ == 0) { distinctCharCount++; } maxLength = Math.max(maxLength, j - i + 1); } return maxLength; }} Sliding Window1234567891011121314151617181920class Solution { public int lengthOfLongestSubstringTwoDistinct(String s) { Map<Character, Integer> charToLastIndexMap = new HashMap<>(); int i = -1, maxLength = 0; for (int j = 0; j < s.length(); j++) { char c = s.charAt(j); if (charToLastIndexMap.size() == 2 && !charToLastIndexMap.containsKey(c)) { // 当前为第三个不同的字符 i = Collections.min(charToLastIndexMap.values()); charToLastIndexMap.remove(s.charAt(i)); } maxLength = Math.max(maxLength, j - i); charToLastIndexMap.put(c, j); } return maxLength; }} Reference159. Longest Substring with At Most Two Distinct Characters