From 9a4cee05f76d740357fcf949ebc93039672db458 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Fri, 10 Jan 2025 15:05:12 +0800 Subject: [PATCH] 20250110 finished. --- src/problem/mod.rs | 2 + ...an_be_rearranged_to_contain_a_string_ii.rs | 67 +++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 src/problem/p3298_count_substrings_that_can_be_rearranged_to_contain_a_string_ii.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index d6ac9d1..4d006cd 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -422,3 +422,5 @@ mod p3019_number_of_changing_keys; mod p2264_largest_3_same_digit_number_in_string; mod p3297_count_substrings_that_can_be_rearranged_to_contain_a_string_i; + +mod p3298_count_substrings_that_can_be_rearranged_to_contain_a_string_ii; diff --git a/src/problem/p3298_count_substrings_that_can_be_rearranged_to_contain_a_string_ii.rs b/src/problem/p3298_count_substrings_that_can_be_rearranged_to_contain_a_string_ii.rs new file mode 100644 index 0000000..cb7e076 --- /dev/null +++ b/src/problem/p3298_count_substrings_that_can_be_rearranged_to_contain_a_string_ii.rs @@ -0,0 +1,67 @@ +/** + * [3298] Count Substrings That Can Be Rearranged to Contain a String II + */ +pub struct Solution {} + +// submission codes start here +use std::collections::HashMap; + +impl Solution { + pub fn valid_substring_count(word1: String, word2: String) -> i64 { + let word1: Vec = word1.chars().collect(); + let mut word_map = HashMap::with_capacity(26); + for c in word2.chars() { + let entry = word_map.entry(c).or_insert(0); + *entry -= 1; + } + + let mut result = 0; + let mut count = word_map.iter().filter(|c| c.1 < &0).count(); + + let mut right = 0; + for left in 0..word1.len() { + while right < word1.len() && count > 0 { + let entry = word_map.entry(word1[right]).or_insert(0); + *entry += 1; + if *entry == 0 { + count -= 1; + } + right += 1; + } + + if count == 0 { + result += (word1.len() - right + 1) as i64; + } + let entry = word_map.entry(word1[left]).or_insert(0); + *entry -= 1; + if *entry == -1 { + count += 1; + } + } + + result + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_3298() { + assert_eq!( + 1, + Solution::valid_substring_count("bcca".to_owned(), "abc".to_owned()) + ); + assert_eq!( + 10, + Solution::valid_substring_count("abcabc".to_owned(), "abc".to_owned()) + ); + assert_eq!( + 0, + Solution::valid_substring_count("abcabc".to_owned(), "aaabc".to_owned()) + ); + } +}