Skip to content

Commit 9729740

Browse files
committed
Add Substring Anagrams
1 parent b2d4105 commit 9729740

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
fun substringAnagrams(s: String, t: String): Int {
2+
val lenS = s.length
3+
val lenT = t.length
4+
if (lenT > lenS) {
5+
return 0
6+
}
7+
var count = 0
8+
val expectedFreqs = IntArray(26)
9+
val windowFreqs = IntArray(26)
10+
// Populate 'expected_freqs' with the characters in string 't'.
11+
for (c in t) {
12+
expectedFreqs[c - 'a']++
13+
}
14+
var left = 0
15+
var right = 0
16+
while (right < lenS) {
17+
// Add the character at the right pointer to 'window_freqs'
18+
// before sliding the window.
19+
windowFreqs[s[right] - 'a']++
20+
// If the window has reached the expected fixed length, we
21+
// advance the left pointer as well as the right pointer to
22+
// slide the window.
23+
if (right - left + 1 == lenT) {
24+
if (windowFreqs.contentEquals(expectedFreqs)) {
25+
count++
26+
}
27+
// Remove the character at the left pointer from
28+
// 'window_freqs' before advancing the left pointer.
29+
windowFreqs[s[left] - 'a']--
30+
left++
31+
}
32+
right++
33+
}
34+
return count
35+
}

0 commit comments

Comments
 (0)