Skip to content

Commit 0fd93a9

Browse files
committed
Update 1297_Maximum_Number_of_Occurrences_of_a_Substring.java
1 parent b8a6ad8 commit 0fd93a9

File tree

1 file changed

+20
-17
lines changed

1 file changed

+20
-17
lines changed
Lines changed: 20 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,30 @@
11
class Solution {
22
public int maxFreq(String s, int maxLetters, int minSize, int maxSize) {
3-
int result = 0;
4-
Map<String, Integer> freq = new HashMap<>();
3+
Map<Character, Integer> m = new HashMap<>();
4+
Map<String, Integer> substrings = new HashMap<>();
5+
int result = 0, left = 0, right = 0;
56

6-
for (int i = 0; i < s.length() - minSize + 1; i++) {
7-
String str = s.substring(i, i + minSize);
7+
while (right < s.length()) {
8+
char r = s.charAt(right);
9+
m.put(r, m.getOrDefault(r, 0) + 1);
10+
++right;
811

9-
if (isValid(str, maxLetters)) {
10-
freq.put(str, freq.getOrDefault(str, 0) + 1);
11-
result = Math.max(result, freq.get(str));
12+
if (right - left > minSize) {
13+
char l = s.charAt(left);
14+
m.put(l, m.get(l) - 1);
15+
if (m.get(l) == 0) {
16+
m.remove(l);
17+
}
18+
++left;
1219
}
13-
}
14-
15-
return result;
16-
}
1720

18-
private boolean isValid(String s, int maxLetters) {
19-
Set<Character> set = new HashSet<>();
20-
21-
for (char c : s.toCharArray()) {
22-
set.add(c);
21+
if (m.size() <= maxLetters && right - left >= minSize) {
22+
String substr = s.substring(left, right);
23+
substrings.put(substr, substrings.getOrDefault(substr, 0) + 1);
24+
result = Math.max(result, substrings.get(substr));
25+
}
2326
}
2427

25-
return set.size() <= maxLetters;
28+
return result;
2629
}
2730
}

0 commit comments

Comments
 (0)