Given a string, find the length of the longest substring T that contains at most k distinct characters. 「Example 1:」 Input: s = "eceba", k = 2 Output: 3 Explanation: T is "ece" which its length is 3. 「Example 2:」
Given a string, find the length of the longest substring T that contains at most k distinct characters. For example, Given s= “eceba” and k = 2, T is"ece" which its length is 3. 我的做法:维护一个window,r移动到超出k distinct character限制是更新max,然后移动l使distinct character <=k...
我的做法:维护一个window,r移动到超出k distinct character限制是更新max,然后移动l使distinct character <=k; 这种做法更新max只发生在超出限制的时候,有可能永远都没有超出限制,所以while loop完了之后要补上一个max的更新 1publicclassSolution {2publicintlengthOfLongestSubstringKDistinct(String s,intk) {3intl...
本题和Longest Substring with At Most Two Distinct Characters很类似,代码如下: 1publicclassSolution {2publicintlengthOfLongestSubstringKDistinct(String s,intk) {3intlen = 0;4intlo = 0;5inthi = 0;6if(s.length()==0)returnlen;7Map<Character,Integer> map =newHashMap<>();8while(hi<s.leng...
340. Longest Substring with At Most K Distinct Characters 这两道都是经典题目,思路是sliding window + hashMap/HashSet. 具体3用HashSet, 340用HashMap。 题目不难,但不容易一次写对。我在面试的时候就忘了一点。 下面分析一下这两道题容易错的地方。
Given a string, find the length of the longest substring T that contains at mostkdistinct characters. For example, Given s =“eceba”and k = 2, T is "ece" which its length is 3. Solution Slide window, O(n), S(1) 很直观的做法,tricky的地方是,如果当前distinct > k,需要将winStart向...
Given a string, find the length of the longest substring T that contains at most k distinct characters. 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 ...
Given a string, find the length of the longest possible substring in it that has exactly K distinct characters. If there is no possible substring then print -1. You can assume that K is less than or equal to the length of the given string.
What should be returned if no substring meets the criteria? Return 0. What should be returned if s is empty? Return 0 since there are no substrings. Are the characters in the string case-sensitive? Yes, treat uppercase and lowercase letters as distinct characters. HAPPY CASE Input: ...
Given a string, find the length of the longest substring T that contains at most 2 distinct characters. For example, Givens = “eceba”, T is"ece"which its length is 3. 哈希表法 复杂度 时间O(N) 空间 O(1) 思路 我们遍历字符串时用一个哈希表,但这个哈希表只记录两个东西,一个字母和它...