```
int lengthOfLongestSubstringTwoDistinct(string s) {
int l = 0, r = 0, freqs[256]{};
for (int num = 0; r < s.length(); r++) { // maintaining a sliding window: [l, r]
if (freqs[s[r]]++ == 0) { num++; } // num is the number of distinct chars
if (num > 2 && --freqs[s[l++]] == 0) { num--; } // window size only increases if containing no more than 2 chars
}
return r - l;
}
```