Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit f52aafa

Browse files
authored
Create Count Complete Substrings.java
1 parent 9c60e43 commit f52aafa

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

Medium/Count Complete Substrings.java

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
class Solution {
2+
public int countCompleteSubstrings(String word, int k) {
3+
int count = 0;
4+
StringBuilder sb = new StringBuilder();
5+
int n = word.length();
6+
for (int i = 0; i < n; i++) {
7+
sb.append(word.charAt(i));
8+
if (i < n - 1 && Math.abs(word.charAt(i) - word.charAt(i + 1)) > 2) {
9+
count += calculateSubstrings(sb.toString(), k);
10+
sb.setLength(0);
11+
}
12+
}
13+
count += calculateSubstrings(sb.toString(), k);
14+
return count;
15+
}
16+
17+
private int calculateSubstrings(String s, int k) {
18+
int count = 0;
19+
int n = s.length();
20+
for (int i = 1; i <= 26; i++) {
21+
int len = k * i;
22+
int[] freq = new int[26];
23+
if (len > n) {
24+
break;
25+
}
26+
for (int j = 0; j < len; j++) {
27+
freq[s.charAt(j) - 'a']++;
28+
}
29+
if (check(freq, i, k)) {
30+
count++;
31+
}
32+
for (int j = len; j < n; j++) {
33+
freq[s.charAt(j - len) - 'a']--;
34+
freq[s.charAt(j) - 'a']++;
35+
if (check(freq, i, k)) {
36+
count++;
37+
}
38+
}
39+
}
40+
return count;
41+
}
42+
43+
private boolean check(int[] freq, int i, int k) {
44+
for (int value : freq) {
45+
if (value == 0) {
46+
continue;
47+
}
48+
if (value != k) {
49+
return false;
50+
}
51+
}
52+
return true;
53+
}
54+
}

0 commit comments

Comments
 (0)