Skip to content

Commit

Permalink
Add problem 1638: Count Substrings That Differ by One Character
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Oct 5, 2023
1 parent eb4bfad commit 200fe9f
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

// See <https://leetcode.com/problems/count-substrings-that-differ-by-one-character/discuss/917985/JavaC%2B%2BPython-Time-O(nm)-Space-O(1)>.

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::<super::Solution>();
}
}
Original file line number Diff line number Diff line change
@@ -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<S: Solution>() {
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);
}
}
}

0 comments on commit 200fe9f

Please sign in to comment.