forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0567-permutation-in-string.rs
45 lines (38 loc) · 1.29 KB
/
0567-permutation-in-string.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
implSolution{
pubfncheck_inclusion(s1:String,s2:String) -> bool{
if s1.len() > s2.len(){
returnfalse;
}
let(mut s1_cnt,mut s2_cnt) = ([0;26],[0;26]);
for i in0..s1.len(){
s1_cnt[s1.chars().nth(i).unwrap()asusize - 'a'asusize] += 1;
s2_cnt[s2.chars().nth(i).unwrap()asusize - 'a'asusize] += 1;
}
letmut matches = 0;
for i in0..26{
matches = if s1_cnt[i] == s2_cnt[i]{ matches + 1}else{ matches };
}
letmut l = 0;
for r in s1.len()..s2.len(){
if matches == 26{
returntrue;
}
letmut index = s2.chars().nth(r).unwrap()asusize - 'a'asusize;
s2_cnt[index] += 1;
if s1_cnt[index] == s2_cnt[index]{
matches += 1;
}elseif s1_cnt[index] + 1 == s2_cnt[index]{
matches -= 1;
}
index = s2.chars().nth(l).unwrap()asusize - 'a'asusize;
s2_cnt[index] -= 1;
if s1_cnt[index] == s2_cnt[index]{
matches += 1;
}elseif s1_cnt[index] - 1 == s2_cnt[index]{
matches -= 1;
}
l += 1;
}
matches == 26
}
}