2.Longest Substring with K Distinct Characters 2.1 问题描述 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...
Given a string S, find the length of the longest substring T that contains at most two distinct characters. Given S = “eceba”, T is “ece” which its length is 3. 下面从解释到代码完全照抄达达 http://www.danielbit.com/blog/puzzle/leetcode/leetcode-longest-substring-with-at-most-two...
5. 我的做法:维护一个window,r移动到超出k distinct character限制是更新max,然后移动l使distinct character <=k; 这种做法更新max只发生在超出限制的时候,有可能永远都没有超出限制,所以while loop完了之后要补上一个max的更新 1publicclassSolution {2publicintlengthOfLongestSubstringKDistinct(String s,intk) {...
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.
publicintlengthOfLongestSubstringKDistinct(Strings,intsize){char[]sArray=s.toCharArray();Map<Character,Integer>map=newHashMap<Character,Integer>();// key is character, value is its countintlocalLen=0;intmaxLen=0;intstart=0;for(inti=0;isize){localLen=i-start;if(localLen>maxLen){maxLen...
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 most 2 distinct characters. For example, Givens = “eceba”, T is"ece"which its length is 3. 哈希表法 复杂度 时间O(N) 空间 O(1) 思路 我们遍历字符串时用一个哈希表,但这个哈希表只记录两个东西,一个字母和它...
3. 出现第三种char的时候,i - (p1+1) + 1 = i- p1 直接计算出当前substring长度。同时保证p1<=p2. public class Solution { public int lengthOfLongestSubstringTwoDistinct(String s) { if(s == null || s.length() == 0) return 0; ...