Given a string S, find the length of the longest substring T that contains at most two distinct characters.
For example,
Given S = “eceba”,
T is “ece” which its length is 3.
var lengthOfLongestSubstringTwoDistinct = function (s) {
var res = 0,
m = new Map(),
c, left = 0;
for (var i = 0, len = s.length; i < len; i++) {
c = s.charAt(i);
m.set(c, m.has(c) ? m.get(c) + 1 : 1);
if (m.size > 2) {
if (m.get(s.charAt(left)) == 1) m.delete(s.charAt(left));
left++;
}
res = Math.max(res, i - left + 1);
}
return res;
}