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.
We just need to compare the substring of t and s and see if the difference is 1.
We can set up two pointers, both pointing to the same index of s and t. While the pointers move forward, we would accumulate the difference, if the difference is larger than one, which cannot be counted, we would break the loop.
We would try to use the above method for all the indexes of s and t.
class Solution {
public:
int countSubstrings(string s, string t) {
int ans = 0;
for(int i = 0; i < t.size(); i++){
for(int j = 0; j < s.size(); j++){
int x = i;
int y = j;
int diff = 0;
while(x < t.size() && y < s.size()){
if(t[x] != s[y])diff++;
if(diff == 1)ans++;
if(diff == 2)break;
x++;
y++;
}
}
}
return ans;
}
};