1638. Count Substrings That Differ by One Character
Given two strings
s
andt
, find the number of ways you can choose a non-empty substring ofs
and replace a single character by a different character such that the resulting substring is a substring oft
. In other words, find the number of substrings ins
that differ from some substring int
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.(A substring is a contiguous sequence of characters within a string.)
Return the number of substrings that satisfy the condition above.
I had no clue when I first saw the question. My only thought was the brute-force way, checking every pair of substring and manualy increment the counter for the number of pairs that meets the requirements. I was too lazy to implement it myself and turend to discussion for help. It turns out I was right. Everyone is using the brute-force way. Yet, one solution has caught my attention:
class Solution {
public:
int helper(string& s, string& t, int i, int j){
int res = 0, prev = 0, cur = 0;
for(; i < s.size() && j < t.size(); i++, j++){
cur++;
if(s[i] != t[j])
prev = cur, cur = 0;
res += prev;
}
return res;
}
int countSubstrings(string s, string t) {
int res = 0;
for(int i = 0; i < s.size(); i++)
res += helper(s, t, i, 0);
for(int i = 1; i < t.size(); i++)
res += helper(s, t, 0, i);
return res;
}
};
This is my solution after Lee god's post. His solution was very elegant and efficient, achieving a time complexity of only O(nm) instead of )(n^3).
Here is my attempt to explain the implementation:
We slide one string over the other, demonstrated with the two for loops in the main function, counting the number of pairs that satisfy the requirements by starting at the same index(*after the sliding) and incrementing at the same pace. Thus, we can achieve all combinations of substring at an effective rate.
As for how to determine the number of pairs in each "slide", in each pair of the satisfying substrings, they are divided into two parts: prev & cur.
1) prev: the first part of the substrings that are identical in both;
2) cur: the second part of the substrings that are different by one charcter at front
By checking whether the current two characters in the two strings should can be added to the tail in cur or replacing prev with cur and starting a new cur, we will be able to find out the total number of satisfying paris.
Note that here we are incrementing the result by the length of prev instead of only 1, as we can dynamically choose the postfix-substring in prev that still satisfy the reqruirements, resulting in a >= 1 combination(s).