Simple solution with keeping next boundary (10 lines if condensed)


  • 1
    L

    Basically keep the next left boundary in cl (candidate left). And use hashmap to make sure that there are only two distinct characters in current window.

    function lengthOfLongestSubstringTwoDistinct(s) {
        var map = {};
        var l = 0; // boundary of current window
        var cl = 0; // candidate of next l
        var max = 0;
        
        for (var i = 0; i < s.length; i++) {
            if (!map[s[i]] && Object.keys(map).length === 2) {
                l = cl;
                delete map[s[cl - 1]];
            }
            map[s[i]] = true;
            if (s[i] !== s[cl]) {
                cl = i;
            }
            max = Math.max(i - l + 1, max);
        }
        return max;
    }

  • 0
    L

    Condensed version

    function lengthOfLongestSubstringTwoDistinct(s) {
        var map = {}, l = 0, cl = 0;
        return s.split('').reduce((prev, v, i) => {
            if (!map[v] && Object.keys(map).length === 2) l = cl;
            delete map[s[l - 1]];
            map[v] = true;
            if (v !== s[cl]) cl = i;
            return Math.max(i - l + 1, prev);
        }, 0);
    }

  • 0
    L

    Golang version

    func lengthOfLongestSubstringTwoDistinct(s string) int {
        m := make(map[rune]struct{})
        l := 0
        cl := 0
        max := 0
        
        for i, v := range s {
            if _, ok := m[v]; !ok && len(m) == 2 {
                l = cl
                delete(m, rune(s[cl - 1]))
            }
            m[v] = struct{}{}
            if v != rune(s[cl]) {
                cl = i
            }
            if i - l + 1 > max {
                max = i - l + 1
            }
        }
        return max
    }

Log in to reply
 

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