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
andt
consist of lowercase English letters only.
class Solution:
def countSubstrings(self, s: str, t: str) -> int:
m, n = len(s), len(t)
ans = 0
for i in range(m):
for j in range(n):
if s[i] != t[j]:
l = r = 1
while i - l >= 0 and j - l >= 0 and s[i - l] == t[j - l]:
l += 1
while i + r < m and j + r < n and s[i + r] == t[j + r]:
r += 1
ans += l * r
return ans
class Solution {
public int countSubstrings(String s, String t) {
int m = s.length(), n = t.length();
int ans = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (s.charAt(i) != t.charAt(j)) {
int l = 1, r = 1;
while (i - l >= 0 && j - l >= 0 && s.charAt(i - l) == t.charAt(j - l)) {
++l;
}
while (i + r < m && j + r < n && s.charAt(i + r) == t.charAt(j + r)) {
++r;
}
ans += l * r;
}
}
}
return ans;
}
}
class Solution {
public:
int countSubstrings(string s, string t) {
int m = s.size(), n = t.size();
int ans = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (s[i] == t[j]) continue;
int l = 1, r = 1;
while (i - l >= 0 && j - l >= 0 && s[i - l] == t[j - l]) ++l;
while (i + r < m && j + r < n && s[i + r] == t[j + r]) ++r;
ans += l * r;
}
}
return ans;
}
};
func countSubstrings(s string, t string) int {
m, n := len(s), len(t)
ans := 0
for i := range s {
for j := range t {
if s[i] == t[j] {
continue
}
l, r := 1, 1
for i-l >= 0 && j-l >= 0 && s[i-l] == t[j-l] {
l++
}
for i+r < m && j+r < n && s[i+r] == t[j+r] {
r++
}
ans += l * r
}
}
return ans
}