2024/10/12 灵茶题单 滑动窗口
This commit is contained in:
parent
7baab96a2b
commit
2b77624088
|
@ -0,0 +1,59 @@
|
|||
package com.cool.ling_cha_mount.sliding_windows;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Created with IntelliJ IDEA.
|
||||
*
|
||||
* @Author: Cool
|
||||
* @Date: 2024/10/12/17:17
|
||||
* @Description: 1297. 子串的最大出现次数
|
||||
* Level 7
|
||||
* Hard 2
|
||||
* Score 1748
|
||||
*/
|
||||
public class Num1297 {
|
||||
|
||||
public int maxFreq(String s, int maxLetters, int minSize, int maxSize) {
|
||||
Map<String, Integer> map = new HashMap<>();
|
||||
int[] count = new int[26];
|
||||
char[] chars = s.toCharArray();
|
||||
int num = 0;
|
||||
for (int i = 0; i < minSize; i++) {
|
||||
if (++count[chars[i] - 'a'] == 1) {
|
||||
num++;
|
||||
}
|
||||
}
|
||||
if (num <= maxLetters) {
|
||||
String str = s.substring(0, minSize);
|
||||
map.put(str, 1);
|
||||
}
|
||||
for (int i = minSize; i < chars.length; i++) {
|
||||
char left = chars[i - minSize];
|
||||
char right = chars[i];
|
||||
if (--count[left - 'a'] == 0) {
|
||||
num--;
|
||||
}
|
||||
if (++count[right - 'a'] == 1) {
|
||||
num++;
|
||||
}
|
||||
if (num <= maxLetters) {
|
||||
String str = s.substring(i - minSize + 1, i + 1);
|
||||
map.put(str, map.getOrDefault(str, 0) + 1);
|
||||
}
|
||||
}
|
||||
int res = 0;
|
||||
for (Map.Entry<String, Integer> entry : map.entrySet()) {
|
||||
res = Math.max(res, entry.getValue());
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
maxFreq("aababcaab", 2, 3, 4);
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue