Skip to content

Commit 1cf3f23

Browse files
authored
Create 0567-permutation-in-string.rs
1 parent 73882c7 commit 1cf3f23

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

rust/0567-permutation-in-string.rs

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
impl Solution {
2+
pub fn check_inclusion(s1: String, s2: String) -> bool {
3+
if s1.len() > s2.len() {
4+
return false;
5+
}
6+
7+
let (mut s1_cnt, mut s2_cnt) = ([0; 26], [0; 26]);
8+
for i in 0..s1.len() {
9+
s1_cnt[s1.chars().nth(i).unwrap() as usize - 'a' as usize] += 1;
10+
s2_cnt[s2.chars().nth(i).unwrap() as usize - 'a' as usize] += 1;
11+
}
12+
13+
let mut matches = 0;
14+
for i in 0..26 {
15+
matches = if s1_cnt[i] == s2_cnt[i] { matches + 1 } else { matches };
16+
}
17+
18+
let mut l = 0;
19+
for r in s1.len()..s2.len() {
20+
if matches == 26 {
21+
return true;
22+
}
23+
24+
let mut index = s2.chars().nth(r).unwrap() as usize - 'a' as usize;
25+
s2_cnt[index] += 1;
26+
if s1_cnt[index] == s2_cnt[index] {
27+
matches += 1;
28+
} else if s1_cnt[index] + 1 == s2_cnt[index]{
29+
matches -= 1;
30+
}
31+
32+
index = s2.chars().nth(l).unwrap() as usize - 'a' as usize;
33+
s2_cnt[index] -= 1;
34+
if s1_cnt[index] == s2_cnt[index] {
35+
matches += 1;
36+
} else if s1_cnt[index] - 1 == s2_cnt[index]{
37+
matches -= 1;
38+
}
39+
40+
l += 1;
41+
}
42+
43+
matches == 26
44+
}
45+
}

0 commit comments

Comments
 (0)