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

Posted aaronliu1991

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 340. Longest Substring with At Most K Distinct Characters相关的知识,希望对你有一定的参考价值。

最多有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的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 340. Longest Substring with At Most K Distinct Characters 最多有K个不同字符的最长子串

leetCode- Longest Palindromic Substring

LeetCode题解 #5 Longest Palindromic Substring

leetcode--5. Longest Palindromic Substring

#Leetcode# 5. Longest Palindromic Substring

LeetCode #5 Longest Palindrome