From 2b776240885b8bcd99fefe6c4a8241bb0907cfd2 Mon Sep 17 00:00:00 2001 From: Cool <747682928@qq.com> Date: Sat, 12 Oct 2024 17:33:48 +0800 Subject: [PATCH] =?UTF-8?q?2024/10/12=20=E7=81=B5=E8=8C=B6=E9=A2=98?= =?UTF-8?q?=E5=8D=95=20=E6=BB=91=E5=8A=A8=E7=AA=97=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../sliding_windows/Num1297.java | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 src/main/java/com/cool/ling_cha_mount/sliding_windows/Num1297.java diff --git a/src/main/java/com/cool/ling_cha_mount/sliding_windows/Num1297.java b/src/main/java/com/cool/ling_cha_mount/sliding_windows/Num1297.java new file mode 100644 index 0000000..37edbf2 --- /dev/null +++ b/src/main/java/com/cool/ling_cha_mount/sliding_windows/Num1297.java @@ -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 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 entry : map.entrySet()) { + res = Math.max(res, entry.getValue()); + } + return res; + } + + @Test + public void test() { + maxFreq("aababcaab", 2, 3, 4); + } +}