diff --git a/src/lib.rs b/src/lib.rs index 8910d72d..6fa4db48 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1345,6 +1345,7 @@ pub mod problem_1631_path_with_minimum_effort; pub mod problem_1632_rank_transform_of_a_matrix; pub mod problem_1636_sort_array_by_increasing_frequency; pub mod problem_1637_widest_vertical_area_between_two_points_containing_no_points; +pub mod problem_1638_count_substrings_that_differ_by_one_character; pub mod problem_1640_check_array_formation_through_concatenation; pub mod problem_1641_count_sorted_vowel_strings; pub mod problem_1642_furthest_building_you_can_reach; diff --git a/src/problem_1638_count_substrings_that_differ_by_one_character/iterative.rs b/src/problem_1638_count_substrings_that_differ_by_one_character/iterative.rs new file mode 100644 index 00000000..220b2be7 --- /dev/null +++ b/src/problem_1638_count_substrings_that_differ_by_one_character/iterative.rs @@ -0,0 +1,55 @@ +pub struct Solution; + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +// See . + +impl Solution { + fn helper(s: &[u8], t: &[u8], result: &mut i32) { + let mut length_1 = 0; + let mut length_2 = 0; + + for (left, right) in s.iter().zip(t) { + length_2 += 1; + + if left != right { + length_1 = length_2; + length_2 = 0; + } + + *result += length_1; + } + } + + pub fn count_substrings(s: String, t: String) -> i32 { + let s = s.as_bytes(); + let t = t.as_bytes(); + let mut result = 0; + + for i in 0..t.len() { + Self::helper(s, &t[i..], &mut result); + } + + for i in 1..s.len() { + Self::helper(&s[i..], t, &mut result); + } + + result + } +} + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl super::Solution for Solution { + fn count_substrings(s: String, t: String) -> i32 { + Self::count_substrings(s, t) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_1638_count_substrings_that_differ_by_one_character/mod.rs b/src/problem_1638_count_substrings_that_differ_by_one_character/mod.rs new file mode 100644 index 00000000..d87fb17c --- /dev/null +++ b/src/problem_1638_count_substrings_that_differ_by_one_character/mod.rs @@ -0,0 +1,18 @@ +pub mod iterative; + +pub trait Solution { + fn count_substrings(s: String, t: String) -> i32; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [(("aba", "baba"), 6), (("ab", "bb"), 3)]; + + for ((s, t), expected) in test_cases { + assert_eq!(S::count_substrings(s.to_string(), t.to_string()), expected); + } + } +}