From a8b74b82a9a7d4749e4eed0afdf032f2fbac59f0 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Tue, 12 Nov 2024 11:58:42 +0800 Subject: [PATCH] 20241112 finished. --- src/problem/mod.rs | 2 + ..._substrings_that_satisfy_k_constraint_i.rs | 76 +++++++++++++++++++ 2 files changed, 78 insertions(+) create mode 100644 src/problem/p3258_count_substrings_that_satisfy_k_constraint_i.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index bd7de44..9e64e4e 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -310,3 +310,5 @@ mod p3242_design_neighbor_sum_service; mod p540_single_element_in_a_sorted_array; mod p1547_minimum_cost_to_cut_a_stick; + +mod p3258_count_substrings_that_satisfy_k_constraint_i; diff --git a/src/problem/p3258_count_substrings_that_satisfy_k_constraint_i.rs b/src/problem/p3258_count_substrings_that_satisfy_k_constraint_i.rs new file mode 100644 index 0000000..3d5230a --- /dev/null +++ b/src/problem/p3258_count_substrings_that_satisfy_k_constraint_i.rs @@ -0,0 +1,76 @@ +/** + * [3258] Count Substrings That Satisfy K-Constraint I + */ +pub struct Solution {} + +// submission codes start here + +impl Solution { + pub fn count_k_constraint_substrings(s: String, k: i32) -> i32 { + let s: Vec = s.chars().map(|x| x.to_digit(10).unwrap()).collect(); + + let mut result = 0; + let mut windows = Vec::with_capacity(s.len()); + + let mut window = (0, 0); + for i in 0..s.len() { + if s[i] == 0 { + window.0 += 1; + } else { + window.1 += 1; + } + + windows.push(window); + if window.0 <= k || window.1 <= k { + result += 1; + } + } + + for i in 1..s.len() { + for length in 1..=s.len() { + if i >= length { + if s[i] == 0 { + windows[length - 1].0 += 1; + } else { + windows[length - 1].1 += 1; + } + + if s[i - length] == 0 { + windows[length - 1].0 -= 1; + } else { + windows[length - 1].1 -= 1; + } + + if windows[length - 1].0 <= k || windows[length - 1].1 <= k { + result += 1; + } + } + } + } + + result + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_3258() { + assert_eq!( + 12, + Solution::count_k_constraint_substrings("10101".to_owned(), 1) + ); + assert_eq!( + 25, + Solution::count_k_constraint_substrings("1010101".to_owned(), 2) + ); + assert_eq!( + 15, + Solution::count_k_constraint_substrings("11111".to_owned(), 1) + ); + } +}