function lengthOfLongestSubstringKDistinct(s, k) {
if(s==='' || k == 0) return 0;
let left = 0;
let right = 0;
let res = 0
const map = new Map();
for(;right < s.length; right++) {
map.set(s[right], right)
if(map.size > k) {
let minVal = Infinity;
let minKey = '';
map.forEach((val,key) => {
if(val < minVal) {
minVal = val;
minKey = key;
}
})
map.delete(minKey);
left = minVal + 1
}
res = Math.max(res, right - left + 1)
}
return res;
}
function lengthOfLongestSubstringKDistinct2(s, k) {
if(s==='' || k == 0) return 0;
let left = 0;
let right = 0;
let res = 0
const map = new Map();
for(;right < s.length; right++) {
if(map.get(s[right])) {
map.set(s[right], map.get(s[right])+1)
}else {
map.set(s[right], 1)
}
if(map.size > k) {
let val = map.get(s[left])
while(val > 0) {
val--;
left++
}
map.delete(s[left])
}
res = Math.max(res, right - left + 1)
}
return res;
}
console.log(lengthOfLongestSubstringKDistinct2('daaaaffsd',2))