C++ Very Clear Solution O(1) Space O(n) Time


  • 0
    F
    class Solution {
    public:
        int lengthOfLongestSubstringTwoDistinct(string s) {
            int i = 0, j = 0, m = 0, n = 0, maxlen = 0;
            char cm = 0, cn = 0;
            bool is_j = true;
            while(j < s.size())
                if (is_j)
                {
                    if (m == 0 || s[j] == cm)
                    {
                        cm = s[j];
                        m ++;
                        j ++;
                    }
                    else if (n == 0 || s[j] == cn)
                    {
                        cn = s[j];
                        n ++;
                        j ++;
                    }
                    else
                    {
                        maxlen = max(maxlen, j - i);
                        is_j = false;
                    }
                }
                else
                {
                    if (s[i] == cm)
                        m --;
                    else if (s[i] == cn)
                        n --;
                    if (m == 0 || n == 0)
                        is_j = true;
                    i ++;
                }
            maxlen = max(maxlen, j - i);
            return maxlen;
        }
    };
    

Log in to reply
 

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