Javascript Solution using sliding window approach


  • 0
    M
    var lengthOfLongestSubstringKDistinct = function(s, k) {
        let dict = {};
        let low = 0, ret = 0;
        for (let i = 0; i < s.length; i++) {
            let char = s[i];
            dict[char] = i;
            if (Object.keys(dict).length > k) {
                low = Math.min.apply(null, Object.values(dict));
                delete dict[s[low]];
                low++;
            }
            ret = Math.max(i - low + 1, ret);
        }
        return ret;
    };
    

Log in to reply
 

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