码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 340. Longest Substring with At Most K Distinct Characters

时间:2020-02-28 15:37:15      阅读:51      评论:0      收藏:0      [点我收藏+]

标签:substring   tps   logs   class   bsp   nbsp   its   most   一模一样   

最多有K个不同字符的最长子串。题意就不解释了,参见159题。例子,

Example 1:

Input: s = "eceba", k = 2
Output: 3
Explanation: T is "ece" which its length is 3.

Example 2:

Input: s = "aa", k = 1
Output: 2
Explanation: T is "aa" which its length is 2.

这个题跟159题一模一样,无非是把最多两个字母改成了最多K个字母。还是sliding window的思路做。

时间O(n)

空间O(1)

 1 /**
 2  * @param {string} s
 3  * @param {number} k
 4  * @return {number}
 5  */
 6 var lengthOfLongestSubstringKDistinct = function (s, k) {
 7     let map = new Map();
 8     let left = 0;
 9     let max = 0;
10     for (let right = 0; right < s.length; right++) {
11         map.set(s[right], right);
12         if (map.size > k) {
13             let leftMostChar = null;
14             let leftMostIndex = Infinity;
15             for (let [char, index] of map) {
16                 if (index < leftMostIndex) {
17                     leftMostChar = char;
18                     leftMostIndex = index;
19                 }
20             }
21             map.delete(leftMostChar);
22             left = leftMostIndex + 1;
23         }
24         max = Math.max(max, right - left + 1);
25     }
26     return max;
27 };

 

[LeetCode] 340. Longest Substring with At Most K Distinct Characters

标签:substring   tps   logs   class   bsp   nbsp   its   most   一模一样   

原文地址:https://www.cnblogs.com/aaronliu1991/p/12377253.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!