a simple c++ solution


  • 0
    Z
    class Solution {
    public:
        int lengthOfLongestSubstringTwoDistinct(string s) {
            if (s.size() < 2) return s.size();
            vector<int> cnts(128, 0);
            int left = 0, right = 1, m = 1 + (s[0] != s[1]), ret = 2;
            ++cnts[s[0]];
            ++cnts[s[1]];
            while(true) {
                while (m < 3) {
                    auto len = right - left + 1;
                        if (ret < len) {
                            ret = len;
                        }
                    ++right;
                    if (right == s.size()) {
                        return ret;
                    }
                    if (!cnts[s[right]]++) {
                        ++m;  
                    }
                }
                while(m > 2) {
                    if (!--cnts[s[left++]]) {
                        --m;    
                    }
                }
            }
        }
    };```

Log in to reply
 

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