public class Solution {
// Define p is the index of rightmost element which is distinct from s[i]
// if s[p] == s[i] it means there is only one distinct element
// Define len to be the instant max length of subtring with max2distinct ended with s[i]
public int lengthOfLongestSubstringTwoDistinct(String s) {
if (s.isEmpty()) return 0;
char[] c = s.toCharArray();
int ans = 1;
for (int p = 0, len = 1, i = 1; i < c.length; i++) {
if (c[i] == c[p]  c[p] == c[i  1]) {
len++;
p = i  1;
}
else
if (c[i] == c[i  1]) len++; // no need to update p, increases len
else {
len = i  p; //find a new third distinct character, discard the first
p = i  1;
}
if (ans < len) ans = len;
}
return ans;
}
}
Super Concise and Fast Solution With Explanations  5ms


public class Solution { public int lengthOfLongestSubstringTwoDistinct(String s) { char[] ch = s.toCharArray(); int len = 1, p = 0, ans = Math.min(len, ch.length); for (int i = 1; i < ch.length; i++) { len++; if (ch[p] == ch[i]  ch[p] == ch[i  1]) p = i  1; else if (ch[i] != ch[i  1]) { len = i  p; p = i  1; } ans = Math.max(ans, len); } return ans; } }