diff --git a/src/problem/mod.rs b/src/problem/mod.rs index f2a0127..4d16cba 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -115,4 +115,5 @@ mod p125_valid_palindrome; mod p392_is_subsequence; mod p167_two_sum_ii_input_array_is_sorted; mod p209_minimum_size_subarray_sum; -mod p30_substring_with_concatenation_of_all_words; \ No newline at end of file +mod p30_substring_with_concatenation_of_all_words; +mod p76_minimum_window_substring; \ No newline at end of file diff --git a/src/problem/p76_minimum_window_substring.rs b/src/problem/p76_minimum_window_substring.rs new file mode 100644 index 0000000..0b78eda --- /dev/null +++ b/src/problem/p76_minimum_window_substring.rs @@ -0,0 +1,82 @@ +/** + * [76] Minimum Window Substring + */ +pub struct Solution {} + + +// submission codes start here +use std::collections::HashMap; + +impl Solution { + pub fn min_window(s: String, t: String) -> String { + let mut t_map = HashMap::new(); + + for c in t.chars() { + let entry = t_map.entry(c).or_insert(0); + *entry += 1; + } + + let s : Vec = s.chars().collect(); + let mut s_map = HashMap::new(); + + let (mut i , mut j) = (0, 0); + let mut result_left = 0; + let mut result_length = usize::MAX; + + while j < s.len() { + if t_map.contains_key(&s[j]) { + let entry = s_map.entry(s[j]).or_insert(0); + *entry += 1; + } + + while Solution::check_map(&s_map, &t_map) && i <= j { + if j - i + 1 < result_length { + result_length = j - i + 1; + result_left = i; + } + + if let Some(entry) = s_map.get_mut(&s[i]) { + *entry -= 1; + } + i += 1; + } + + j += 1; + } + + if result_length == usize::MAX { + String::new() + } else { + s[result_left..result_left + result_length].iter().collect() + } + } + + fn check_map(s : &HashMap, t : &HashMap) -> bool { + for (key, value) in t { + match s.get(key) { + Some(real_value) => { + if *value > *real_value { + return false; + } + } + None => { + return false; + } + } + } + + true + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_76() { + assert_eq!("BANC".to_owned(), Solution::min_window("ADOBECODEBANC".to_owned(), "ABC".to_owned())); + } +}