Given a string, find the length of the longest substring T that contains at most 2 distinct characters.
T is "ece" which its length is 3.
class Solution {
public int lengthOfLongestSubstringTwoDistinct(String s) {
if (s.length() <= 2) {
return s.length();
}
int maxLen = 0;
int start = 0, end = 0, count = 0;
int[] map = new int[256];
while (end < s.length()) {
if (map[s.charAt(end)] == 0) {
++count;
}
++map[s.charAt(end)];
++end;
while (count > 2) {
if (map[s.charAt(start)] == 1) {
--count;
}
--map[s.charAt(start)];
++start;
}
maxLen = Math.max(maxLen, end - start);
}
return maxLen;
}
}