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.
Constraints:
1 <= s.length, t.length <= 100
s and t consist of lowercase English letters only.
Solutions
Solution 1
Thinking
Both strings have length at most \(100\). A valid pair differs in exactly one position; extending from that mismatch, the runs of equal characters on each side determine how many cuts work.
Enumerate \((i,j)\) with \(s[i]\ne t[j]\), measure equal spans \(l\) and \(r\), and add \((l+1)(r+1)\).
Solution 1 extends from every mismatch and repeats comparisons. Precompute the longest equal suffix \(f\) ending at \((i,j)\) and the longest equal prefix \(g\) starting there.
Each mismatch then contributes \((f[i][j]+1)(g[i+1][j+1]+1)\) in \(O(mn)\) total time.