```
public int lengthOfLongestSubstringTwoDistinct(String s) {
int i = 0, j = -1, length = 0, count = 0;
HashMap<Character, Integer> visited = new HashMap<Character, Integer>();
while (++j < s.length()) {
char c = s.charAt(j);
if (!visited.containsKey(c) || visited.get(c) < i) count++;
visited.put(c, j);
if (count > 2) {
length = Math.max(length, j - i);
while (visited.get(s.charAt(i)) != i++);
count--;
}
}
return Math.max(length, j - i);
}
```