var lengthOfLongestSubstringKDistinct = function (s, k) {
let n = s.length;
let left = 0;
let right = 0;
let mapping = {};
let res = 0;
while (right < n) {
let c = s[right];
mapping[c] = (mapping[c] || 0) + 1;
right++;
let count = Object.keys(mapping).length;
while (count > k) {
let c = s[left];
mapping[c]--;
if (mapping[c] === 0) {
delete mapping[c];
count--;
}
left++;
}
// 更新结果(移到这里)
res = Math.max(res, right - left);
}
return res;
};