Skip to content

Commit ce7a566

Browse files
Leetcode solution to the problem: find-all-anagrams-in-a-string
1 parent a9c9e8d commit ce7a566

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

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

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
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+
fn find_anagrams(s: String, p: String) -> Vec<i32> {
38+
let (s_len, p_len) = (s.len(), p.len());
39+
let mut ans = vec![];
40+
if s_len < p_len {
41+
return ans;
42+
}
43+
let mut freq_s = CharVec::new();
44+
let mut freq_p = CharVec::new();
45+
let s = s.chars().collect::<Vec<char>>();
46+
let p = p.chars().collect::<Vec<char>>();
47+
for i in 0..p_len {
48+
freq_s[s[i]] += 1;
49+
freq_p[p[i]] += 1;
50+
}
51+
if freq_s == freq_p {
52+
ans.push(0);
53+
}
54+
/* sliding window with of length p_len */
55+
for i in p_len..s_len {
56+
freq_s[s[i - p_len]] -= 1;
57+
freq_s[s[i]] += 1;
58+
if freq_s == freq_p {
59+
ans.push((i - p_len + 1) as i32);
60+
}
61+
}
62+
ans
63+
}

0 commit comments

Comments
 (0)