Skip to content

Commit 50a39f9

Browse files
committed
add: SubstringAnagrams
1 parent 6a98e78 commit 50a39f9

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
public class SubstringAnagrams {
2+
public int substringAnagrams(String s, String t) {
3+
int lenS = s.length();
4+
int lenT = t.length();
5+
if (lenT > lenS) return 0;
6+
int count = 0;
7+
int[] expectedFreqs = new int[26];
8+
int[] windowFreqs = new int[26];
9+
// Populate 'expected_freqs' with the characters in string 't'.
10+
for (char c : t.toCharArray()) {
11+
expectedFreqs[c - 'a'] += 1;
12+
}
13+
int left, right;
14+
left = right = 0;
15+
while (right < lenS) {
16+
// Add the character at the right pointer to 'window_freqs'
17+
// before sliding the window.
18+
windowFreqs[s.charAt(right) - 'a'] += 1;
19+
// If the window has reached the expected fixed length, we
20+
// advance the left pointer as well as the right pointer to
21+
// slide the window.
22+
if (right - left + 1 == lenT) {
23+
if (compareFreqs(windowFreqs, expectedFreqs)) {
24+
count += 1;
25+
}
26+
// Remove the character at the left pointer from
27+
// 'window_freqs' before advancing the left pointer.
28+
windowFreqs[s.charAt(left) - 'a'] -= 1;
29+
left += 1;
30+
}
31+
right += 1;
32+
}
33+
return count;
34+
}
35+
36+
private boolean compareFreqs(int[] windowFreqs, int[] expectedFreqs) {
37+
for (int i = 0; i < 26; i++) {
38+
if (windowFreqs[i] != expectedFreqs[i]) return false;
39+
}
40+
return true;
41+
}
42+
}

0 commit comments

Comments
 (0)