|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.HashSet; |
| 5 | +import java.util.Map; |
| 6 | +import java.util.Set; |
| 7 | + |
| 8 | +/** |
| 9 | + * 1297. Maximum Number of Occurrences of a Substring |
| 10 | + * |
| 11 | + * Given a string s, return the maximum number of ocurrences of any substring under the following rules: |
| 12 | + * |
| 13 | + * The number of unique characters in the substring must be less than or equal to maxLetters. |
| 14 | + * The substring size must be between minSize and maxSize inclusive. |
| 15 | + * |
| 16 | + * Example 1: |
| 17 | + * Input: s = "aababcaab", maxLetters = 2, minSize = 3, maxSize = 4 |
| 18 | + * Output: 2 |
| 19 | + * Explanation: Substring "aab" has 2 ocurrences in the original string. |
| 20 | + * It satisfies the conditions, 2 unique letters and size 3 (between minSize and maxSize). |
| 21 | + * |
| 22 | + * Example 2: |
| 23 | + * Input: s = "aaaa", maxLetters = 1, minSize = 3, maxSize = 3 |
| 24 | + * Output: 2 |
| 25 | + * Explanation: Substring "aaa" occur 2 times in the string. It can overlap. |
| 26 | + * |
| 27 | + * Example 3: |
| 28 | + * Input: s = "aabcabcab", maxLetters = 2, minSize = 2, maxSize = 3 |
| 29 | + * Output: 3 |
| 30 | + * |
| 31 | + * Example 4: |
| 32 | + * Input: s = "abcde", maxLetters = 2, minSize = 3, maxSize = 3 |
| 33 | + * Output: 0 |
| 34 | + * |
| 35 | + * Constraints: |
| 36 | + * 1 <= s.length <= 10^5 |
| 37 | + * 1 <= maxLetters <= 26 |
| 38 | + * 1 <= minSize <= maxSize <= min(26, s.length) |
| 39 | + * s only contains lowercase English letters. |
| 40 | + * */ |
| 41 | +public class _1297 { |
| 42 | + public static class Solution1 { |
| 43 | + public int maxFreq(String s, int maxLetters, int minSize, int maxSize) { |
| 44 | + int maxFreq = 0; |
| 45 | + for (int size = minSize; size <= maxSize; size++) { |
| 46 | + maxFreq = Math.max(maxFreq, getMaxFreqWithThisSize(s, maxLetters, size)); |
| 47 | + } |
| 48 | + return maxFreq; |
| 49 | + } |
| 50 | + |
| 51 | + private int getMaxFreqWithThisSize(String str, int maxLetters, int size) { |
| 52 | + Map<String, Integer> map = new HashMap<>(); |
| 53 | + for (int i = 0; i <= str.length() - size; i++) { |
| 54 | + String substring = str.substring(i, i + size); |
| 55 | + Set<Character> set = new HashSet<>(); |
| 56 | + for (int j = 0; j < substring.length(); j++) { |
| 57 | + set.add(substring.charAt(j)); |
| 58 | + if (set.size() > maxLetters) { |
| 59 | + break; |
| 60 | + } |
| 61 | + } |
| 62 | + if (set.size() <= maxLetters) { |
| 63 | + map.put(substring, map.getOrDefault(substring, 0) + 1); |
| 64 | + } |
| 65 | + } |
| 66 | + int max = 0; |
| 67 | + for (String key : map.keySet()) { |
| 68 | + max = Math.max(max, map.get(key)); |
| 69 | + } |
| 70 | + return max; |
| 71 | + } |
| 72 | + } |
| 73 | +} |
0 commit comments