题解 | #至多包含K种字符的子串#
至多包含K种字符的子串
https://www.nowcoder.com/practice/04c926ef687340c3842a72edb5c23ede
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @param k int整型 * @return int整型 */ public int longestSubstring (String s, int k) { // write code here int left = 0, right = 0, count = 0, subcount = 0; HashMap<Character, Integer> frequency = new HashMap<>(); while(right<s.length()){ int value = frequency.getOrDefault(s.charAt(right), 0) + 1; frequency.put(s.charAt(right), value); right++; if (value == 1) { count++; } if (count <= k) { subcount = Math.max(subcount, right - left); } if (count > k) { int subValue = frequency.getOrDefault(s.charAt(left), 0) - 1; frequency.put(s.charAt(left), subValue); left++; if (subValue == 0) { count--; } } } return subcount; } }
滑动窗口解法,左右移动
#23届找工作求助阵地##我的实习求职记录#