File tree Expand file tree Collapse file tree 2 files changed +36
-0
lines changed Expand file tree Collapse file tree 2 files changed +36
-0
lines changed Original file line number Diff line number Diff line change 328
328
337|[ House Robber III] ( ./solutions/0337-house-robber-iii.js ) |Medium|
329
329
338|[ Counting Bits] ( ./solutions/0338-counting-bits.js ) |Easy|
330
330
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|
331
332
341|[ Flatten Nested List Iterator] ( ./solutions/0341-flatten-nested-list-iterator.js ) |Medium|
332
333
342|[ Power of Four] ( ./solutions/0342-power-of-four.js ) |Easy|
333
334
343|[ Integer Break] ( ./solutions/0343-integer-break.js ) |Medium|
Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments