Skip to content

Commit 4c57d46

Browse files
authored
Merge pull request #3257 from saurabh10041998/find-anagrams
Create 0438-find-all-anagrams-in-a-string.rs
2 parents 046504a + 8be9562 commit 4c57d46

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

Diff for: rust/0438-find-all-anagrams-in-a-string.rs

+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
use std::ops::{Index, IndexMut};
2+
struct CharVec(Vec<i32>);
3+
4+
impl CharVec {
5+
fn new() -> Self {
6+
Self(vec![0; 26])
7+
}
8+
}
9+
10+
impl Index<char> for CharVec {
11+
type Output = i32;
12+
fn index(&self, index: char) -> &Self::Output {
13+
match index {
14+
'a'..='z' => &self.0[(index as u8 - 'a' as u8) as usize],
15+
_ => panic!("[!!] {} character is not supported in CharVec", index),
16+
}
17+
}
18+
}
19+
20+
impl IndexMut<char> for CharVec {
21+
fn index_mut(&mut self, index: char) -> &mut Self::Output {
22+
match index {
23+
'a'..='z' => &mut self.0[(index as u8 - 'a' as u8) as usize],
24+
_ => panic!("[!!] {} character is not supported in CharVec", index),
25+
}
26+
}
27+
}
28+
29+
impl Eq for CharVec {}
30+
31+
impl PartialEq for CharVec {
32+
fn eq(&self, other: &Self) -> bool {
33+
self.0.eq(&other.0)
34+
}
35+
}
36+
37+
impl Solution {
38+
pub fn find_anagrams(s: String, p: String) -> Vec<i32> {
39+
let (s_len, p_len) = (s.len(), p.len());
40+
let mut ans = vec![];
41+
if s_len < p_len {
42+
return ans;
43+
}
44+
let mut freq_s = CharVec::new();
45+
let mut freq_p = CharVec::new();
46+
let s = s.chars().collect::<Vec<char>>();
47+
let p = p.chars().collect::<Vec<char>>();
48+
for i in 0..p_len {
49+
freq_s[s[i]] += 1;
50+
freq_p[p[i]] += 1;
51+
}
52+
if freq_s == freq_p {
53+
ans.push(0);
54+
}
55+
/* sliding window with of length p_len */
56+
for i in p_len..s_len {
57+
freq_s[s[i - p_len]] -= 1;
58+
freq_s[s[i]] += 1;
59+
if freq_s == freq_p {
60+
ans.push((i - p_len + 1) as i32);
61+
}
62+
}
63+
ans
64+
}
65+
}

0 commit comments

Comments
 (0)