Skip to content

Commit f75eb21

Browse files
committed
Add substring_anagrams
1 parent f3f0806 commit f75eb21

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+
fn substring_anagrams(s: String, t: String) -> i32 {
2+
let len_s = s.len();
3+
let len_t = t.len();
4+
if len_t > len_s {
5+
return 0;
6+
}
7+
let mut count = 0;
8+
let mut expected_freqs = vec![0; 26];
9+
let mut window_freqs = vec![0; 26];
10+
// Populate 'expected_freqs' with the characters in string 't'.
11+
for c in t.bytes() {
12+
expected_freqs[(c - b'a') as usize] += 1;
13+
}
14+
let mut left = 0;
15+
let mut right = 0;
16+
while right < len_s {
17+
// Add the character at the right pointer to 'window_freqs'
18+
// before sliding the window.
19+
window_freqs[(s.as_bytes()[right] - b'a') as usize] += 1;
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 == len_t {
24+
if window_freqs == expected_freqs {
25+
count += 1;
26+
}
27+
// Remove the character at the left pointer from
28+
// 'window_freqs' before advancing the left pointer.
29+
window_freqs[(s.as_bytes()[left] - b'a') as usize] -= 1;
30+
left += 1;
31+
}
32+
right += 1;
33+
}
34+
count
35+
}

0 commit comments

Comments
 (0)