Skip to content

Commit 200fe9f

Browse files
committed
Add problem 1638: Count Substrings That Differ by One Character
1 parent eb4bfad commit 200fe9f

File tree

3 files changed

+74
-0
lines changed

3 files changed

+74
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1345,6 +1345,7 @@ pub mod problem_1631_path_with_minimum_effort;
13451345
pub mod problem_1632_rank_transform_of_a_matrix;
13461346
pub mod problem_1636_sort_array_by_increasing_frequency;
13471347
pub mod problem_1637_widest_vertical_area_between_two_points_containing_no_points;
1348+
pub mod problem_1638_count_substrings_that_differ_by_one_character;
13481349
pub mod problem_1640_check_array_formation_through_concatenation;
13491350
pub mod problem_1641_count_sorted_vowel_strings;
13501351
pub mod problem_1642_furthest_building_you_can_reach;
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
pub struct Solution;
2+
3+
// ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+
// See <https://leetcode.com/problems/count-substrings-that-differ-by-one-character/discuss/917985/JavaC%2B%2BPython-Time-O(nm)-Space-O(1)>.
6+
7+
impl Solution {
8+
fn helper(s: &[u8], t: &[u8], result: &mut i32) {
9+
let mut length_1 = 0;
10+
let mut length_2 = 0;
11+
12+
for (left, right) in s.iter().zip(t) {
13+
length_2 += 1;
14+
15+
if left != right {
16+
length_1 = length_2;
17+
length_2 = 0;
18+
}
19+
20+
*result += length_1;
21+
}
22+
}
23+
24+
pub fn count_substrings(s: String, t: String) -> i32 {
25+
let s = s.as_bytes();
26+
let t = t.as_bytes();
27+
let mut result = 0;
28+
29+
for i in 0..t.len() {
30+
Self::helper(s, &t[i..], &mut result);
31+
}
32+
33+
for i in 1..s.len() {
34+
Self::helper(&s[i..], t, &mut result);
35+
}
36+
37+
result
38+
}
39+
}
40+
41+
// ------------------------------------------------------ snip ------------------------------------------------------ //
42+
43+
impl super::Solution for Solution {
44+
fn count_substrings(s: String, t: String) -> i32 {
45+
Self::count_substrings(s, t)
46+
}
47+
}
48+
49+
#[cfg(test)]
50+
mod tests {
51+
#[test]
52+
fn test_solution() {
53+
super::super::tests::run::<super::Solution>();
54+
}
55+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
pub mod iterative;
2+
3+
pub trait Solution {
4+
fn count_substrings(s: String, t: String) -> i32;
5+
}
6+
7+
#[cfg(test)]
8+
mod tests {
9+
use super::Solution;
10+
11+
pub fn run<S: Solution>() {
12+
let test_cases = [(("aba", "baba"), 6), (("ab", "bb"), 3)];
13+
14+
for ((s, t), expected) in test_cases {
15+
assert_eq!(S::count_substrings(s.to_string(), t.to_string()), expected);
16+
}
17+
}
18+
}

0 commit comments

Comments
 (0)