标签: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