forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
51 lines (49 loc) · 1.51 KB
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Solution {
public int countCompleteSubstrings(String word, int k) {
int n = word.length();
int ans = 0;
for (int i = 0; i < n;) {
int j = i + 1;
while (j < n && Math.abs(word.charAt(j) - word.charAt(j - 1)) <= 2) {
++j;
}
ans += f(word.substring(i, j), k);
i = j;
}
return ans;
}
private int f(String s, int k) {
int m = s.length();
int ans = 0;
for (int i = 1; i <= 26 && i * k <= m; ++i) {
int l = i * k;
int[] cnt = new int[26];
for (int j = 0; j < l; ++j) {
++cnt[s.charAt(j) - 'a'];
}
Map<Integer, Integer> freq = new HashMap<>();
for (int x : cnt) {
if (x > 0) {
freq.merge(x, 1, Integer::sum);
}
}
if (freq.getOrDefault(k, 0) == i) {
++ans;
}
for (int j = l; j < m; ++j) {
int a = s.charAt(j) - 'a';
int b = s.charAt(j - l) - 'a';
freq.merge(cnt[a], -1, Integer::sum);
++cnt[a];
freq.merge(cnt[a], 1, Integer::sum);
freq.merge(cnt[b], -1, Integer::sum);
--cnt[b];
freq.merge(cnt[b], 1, Integer::sum);
if (freq.getOrDefault(k, 0) == i) {
++ans;
}
}
}
return ans;
}
}