#1638

Count Substrings That Differ by One Character

pupil · 555 · lc medium +28 · premium · verified · 72.4% accepted · 1,202 likes · top 82%

Description

Given two strings s and t, count all pairs of substrings — one from s and one from t — that have the same length but differ in exactly one character position. Return the total count.

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.

Code

1
2
3