标签:map end Most Distinct Substring maxLen int let start
最多有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) - 只是一个256位长度的数组
Java实现
1 class Solution { 2 public int lengthOfLongestSubstringKDistinct(String s, int k) { 3 // corner case 4 if (s == null || s.length() == 0) { 5 return 0; 6 } 7 8 // normal case 9 int[] map = new int[256]; 10 int start = 0; 11 int end = 0; 12 int maxLen = Integer.MIN_VALUE; 13 int counter = 0; 14 while (end < s.length()) { 15 char c1 = s.charAt(end); 16 if (map[c1] == 0) { 17 counter++; 18 } 19 map[c1]++; 20 end++; 21 while (counter > k) { 22 char c2 = s.charAt(start); 23 if (map[c2] == 1) { 24 counter--; 25 } 26 map[c2]--; 27 start++; 28 } 29 maxLen = Math.max(maxLen, end - start); 30 } 31 return maxLen; 32 } 33 }
JavaScript实现
1 /** 2 * @param {string} s 3 * @param {number} k 4 * @return {number} 5 */ 6 var lengthOfLongestSubstringKDistinct = function(s, k) { 7 // corner case 8 if (s == null || s.length == 0) { 9 return 0; 10 } 11 12 // normal case 13 let start = 0; 14 let end = 0; 15 let maxLen = -Infinity; 16 let counter = 0; 17 let map = {}; 18 while (end < s.length) { 19 let c1 = s.charAt(end); 20 if (map[c1] == null || map[c1] <= 0) { 21 counter++; 22 } 23 map[c1] = map[c1] + 1 || 1; 24 end++; 25 while (counter > k) { 26 let c2 = s.charAt(start); 27 if (map[c2] == 1) { 28 counter--; 29 } 30 map[c2]--; 31 start++; 32 } 33 maxLen = Math.max(maxLen, end - start); 34 } 35 return maxLen; 36 };
标签:map,end,Most,Distinct,Substring,maxLen,int,let,start 来源: https://www.cnblogs.com/aaronliu1991/p/12377253.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。