Skip to content

Commit d1a09b6

Browse files
committed
Add solution #340
1 parent 85bb78c commit d1a09b6

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -328,6 +328,7 @@
328328
337|[House Robber III](./solutions/0337-house-robber-iii.js)|Medium|
329329
338|[Counting Bits](./solutions/0338-counting-bits.js)|Easy|
330330
339|[Nested List Weight Sum](./solutions/0339-nested-list-weight-sum.js)|Medium|
331+
340|[Longest Substring with At Most K Distinct Characters](./solutions/0340-longest-substring-with-at-most-k-distinct-characters.js)|Medium|
331332
341|[Flatten Nested List Iterator](./solutions/0341-flatten-nested-list-iterator.js)|Medium|
332333
342|[Power of Four](./solutions/0342-power-of-four.js)|Easy|
333334
343|[Integer Break](./solutions/0343-integer-break.js)|Medium|
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* 340. Longest Substring with At Most K Distinct Characters
3+
* https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/
4+
* Difficulty: Medium
5+
*
6+
* Given a string s and an integer k, return the length of the longest substring of s that
7+
* contains at most k distinct characters.
8+
*/
9+
10+
/**
11+
* @param {string} s
12+
* @param {number} k
13+
* @return {number}
14+
*/
15+
var lengthOfLongestSubstringKDistinct = function(s, k) {
16+
const map = new Map();
17+
let result = 0;
18+
let left = 0;
19+
20+
for (let right = 0; right < s.length; right++) {
21+
map.set(s[right], (map.get(s[right]) || 0) + 1);
22+
23+
while (map.size > k) {
24+
map.set(s[left], map.get(s[left]) - 1);
25+
if (map.get(s[left]) === 0) {
26+
map.delete(s[left]);
27+
}
28+
left++;
29+
}
30+
31+
result = Math.max(result, right - left + 1);
32+
}
33+
34+
return result;
35+
};

0 commit comments

Comments
 (0)