forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0076-minimum-window-substring.rs
50 lines (38 loc) · 1.35 KB
/
0076-minimum-window-substring.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
46
47
48
49
50
use std::collections::HashMap;
implSolution{
pubfnmin_window(s:String,t:String) -> String{
let s:Vec<char> = s.chars().collect();
if t == String::new() || s.len() < t.len(){
returnString::new();
}
let(mut l,mut res,mut res_len) = (0,(-1asi32, -1asi32), usize::MAX);
letmut count_t:HashMap<char,u64> = HashMap::new();
letmut window:HashMap<char,u64> = HashMap::new();
for c in t.chars(){
*count_t.entry(c).or_default() += 1;
}
let(mut have, need) = (0, count_t.len());
for r in0..s.len(){
let c = s[r];
*window.entry(c).or_default() += 1;
have += (window.get(&c) == count_t.get(&c))asusize;
while have == need {
if(r - l + 1) < res_len {
res = (l asi32, r asi32);
}
res_len = res_len.min(r - l + 1);
*window.get_mut(&s[l]).unwrap() -= 1;
if window.get(&s[l]) < count_t.get(&s[l]){
have -= 1;
}
l += 1;
}
}
if res.0 > -1 && res.1 > -1{
return s[res.0asusize..=res.1asusize]
.into_iter()
.collect::<String>();
}
String::new()
}
}