A typical sliding window solution.
class Solution { int rec[26]; // for a-z int rec1[26]; // for A-Z int cnt; int &getCnt(char c) { if (c >= 'a' && c <= 'z') return rec[c - 'a']; if (c >= 'A' && c <= 'Z') return rec1[c - 'A']; } public: int lengthOfLongestSubstringTwoDistinct(string s) { std::fill(rec, rec + 26, 0); std::fill(rec1, rec1 + 26, 0); cnt = 0; int ret = 0; int start = 0; for (int i = 0; i < s.length(); i++) { char c = s[i]; if (getCnt(c) == 0) cnt++; getCnt(c)++; int len = i - start + 1; if (cnt <= 2) { ret = std::max(ret, len); } else { while (start < i && cnt > 2) { char nc = s[start]; if (getCnt(nc) == 1) cnt--; getCnt(nc)--; start++; } } } return ret; } };