O(1) space O(n) time C++ solution using pair tracking


  • 0
    V
    int lengthOfLongestSubstringTwoDistinct(string s) {
            int sp = 0, ep = 0, ans = 0;
            vector<char> b;
            while (ep < s.length()) {
                if (b.size() < 2) {
                    if (b.size() == 0 || b[0] != s[ep])
                        b.push_back(s[ep]);
                }
                else {
                    if (b[0] != s[ep] && b[1] != s[ep]) { // new char is encountered
                        sp = ep - 1;
                        while (sp > 0 && s[sp] == s[sp-1])
                            sp--;
                        b[0] != s[ep-1] ? b[0] = s[ep] : b[1] = s[ep];
                    }
                }
                ans = max(ans, ep - sp + 1);
                ep++;
            }
            return ans;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.