1638. Count Substrings That Differ by One Character

Given two strings s and t, find the number of ways you can choose a non-empty substring of s and replace a single character by a different character such that the resulting substring is a substring of t. In other words, find the number of substrings in s that differ from some substring in t by exactly one character.

For example, the underlined substrings in "computer" and "computation" only differ by the 'e'/'a', so this is a valid way.

Return the number of substrings that satisfy the condition above.

A substring is a contiguous sequence of characters within a string.

 

Example 1:

Input: s = "aba", t = "baba"
Output: 6
Explanation: The following are the pairs of substrings from s and t that differ by exactly 1 character:
("aba", "baba")
("aba", "baba")
("aba", "baba")
("aba", "baba")
("aba", "baba")
("aba", "baba")
The underlined portions are the substrings that are chosen from s and t.
​​Example 2:
Input: s = "ab", t = "bb"
Output: 3
Explanation: The following are the pairs of substrings from s and t that differ by 1 character:
("ab", "bb")
("ab", "bb")
("ab", "bb")
​​​​The underlined portions are the substrings that are chosen from s and t.
Example 3:
Input: s = "a", t = "a"
Output: 0

Example 4:

Input: s = "abe", t = "bbc"
Output: 10

 

Constraints:

  • 1 <= s.length, t.length <= 100
  • s and t consist of lowercase English letters only.

Rust Solution

struct Solution;

impl Solution {
    fn count_substrings(s: String, t: String) -> i32 {
        let n = s.len();
        let m = t.len();
        let s: Vec<char> = s.chars().collect();
        let t: Vec<char> = t.chars().collect();
        let mut res = 0;
        for i in 0..n {
            for j in 0..m {
                let k = (n - i).min(m - j);
                let mut diff = 0;
                for d in 0..k {
                    if s[i + d] != t[j + d] {
                        diff += 1;
                    }
                    if diff == 1 {
                        res += 1;
                    }
                }
            }
        }
        res
    }
}

#[test]
fn test() {
    let s = "aba".to_string();
    let t = "baba".to_string();
    let res = 6;
    assert_eq!(Solution::count_substrings(s, t), res);
    let s = "ab".to_string();
    let t = "bb".to_string();
    let res = 3;
    assert_eq!(Solution::count_substrings(s, t), res);
    let s = "a".to_string();
    let t = "a".to_string();
    let res = 0;
    assert_eq!(Solution::count_substrings(s, t), res);
    let s = "abe".to_string();
    let t = "bbc".to_string();
    let res = 10;
    assert_eq!(Solution::count_substrings(s, t), res);
}

Having problems with this solution? Click here to submit an issue on github.