import java.util.*;
public class Solution {
public int numKLenSubstrRepeats (String str, int k) {
// 记录合格子串数量
int count = 0;
// 记录滑动窗口中各种字符的数量
Map<Character,Integer> map = new HashMap<>();
// 滑动窗口默认在字符串首
for (int i = 0; i < k; i++) {
char c = str.charAt(i);
map.put(c ,map.getOrDefault(c,0)+1);
}
// 检查初始窗口
if (hasRepeat(map)) count++;
// 逐步滑动窗口至末尾,实时更新相关数据
for (int i = k; i < str.length(); i++) {
// 更新窗口中的数据,添尾去头
char tail = str.charAt(i);
char head = str.charAt(i-k);
map.put(tail, map.getOrDefault(tail,0)+1); // 添尾
map.put(head, map.get(head)-1); // 去头
// 数据更新完成后再次检查
if (hasRepeat(map)) count++;
}
// 窗口滑动至字符串尾,返回统计结果
return count;
}
// 检查滑动窗口种是否有重复字符
public static boolean hasRepeat(Map<Character,Integer> map) {
for (int count : map.values()) {
if (count > 1) return true;
}
// 所有值均小于等于1
return false;
}
}