My code can work well and easy to understand.

```
public class Solution {
public int lengthOfLongestSubstringTwoDistinct(String s) {
if (s.length() == 0) return 0;
if (s.length() <= 2) return s.length();
char f = ' ',se = s.charAt(0);
int max = 0,count = 1;
for (int i = 1;i < s.length();i++){
if (s.charAt(i) == f || s.charAt(i) == se){
count ++;
if (s.charAt(i) == f){
char c = f;
f = se;
se = c;
}
}else{
f = se;
se = s.charAt(i);
count = 1;
for (int j = i - 1;j >= 0 && s.charAt(j) == f;j--){
count ++;
}
}
max = Math.max(max,count);
}
return max;
}
}
```