340.最多有K个不同字符的最长子串
Given a string, find the length of the longest substring T that contains at most k distinct characters.
Example1:Input: s ="eceba", k =2Output:3Explanation:T is "ece" which its length is 3.Example2:Input: s ="aa", k =1Output:2Explanation:T is "aa" which its length is 2.
方法1:Map统计数量+滑动窗口
publicintlengthOfLongestSubstringKDistinct(String s,int k){int res =0;Map<Character,Integer> map =newHashMap<>();//k:字符,v:字符出现的次数int l =0;//左边窗口的位置for(int i =0; i < s.length(); i++){char c = s.charAt(i);
map.put(c, map.getOrDefault(c,0)+1);while(map.size()> k){//字符的个数已经超过k个了,开始缩小左边窗口char lc = s.charAt(l++);//left charint t = map.get(lc)-1;//left char的数量if(t ==0){//数量为0的时候,key被移除
map.remove(lc);}else{
map.put(lc, t);//-1后数量再次更新进去}}
res =Math.max(res, i - l +1);//计算长度}return res;}
方法2:Map标记位置+滑动窗口
publicintlengthOfLongestSubstringKDistinct(String s,int k){int res =0;Map<Character,Integer> map =newHashMap<>();//k:字符,v:该字符最近一次出现的位置int l =0;//左窗口for(int i =0; i < s.length(); i++){
map.put(s.charAt(i), i);//将当前字符和字符的位置关系记录下来while(map.size()> k){//总的字符开始超过k个//如果 s[l]的 位置和l 不同,说明在[l+1 ... i ]之间又出现了字符s[l],这是不能移除s[l],反之则移除s[l]if(map.get(s.charAt(l))== l) map.remove(s.charAt(l));++l;}
res =Math.max(res, i - l +1);}return res;}