Description
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.
Example 3:
Input: s = "a", t = "a"
Output: 0
Example 4:
Input: s = "abe", t = "bbc"
Output: 10
Constraints:
- 1 <= s.length, t.length <= 100
- s and t consist of lowercase English letters only.
分析
题目的意思是:给定字符串s和字符串t,找出字符串s的子串通过替换一个字符以后,变成t的子串的组合。最笨的办法是穷举出来判断,所以需要双循环,找出的子串只有一个字符不一样,其他的都一样。
代码
class Solution:
def countSubstrings(self, s: str, t: str) -> int:
m=len(s)
n=len(t)
res=0
for i in range(m):
for j in range(n):
diff=0
p=min(m-i,n-j)
for k in range(p):
if(s[i+k]!=t[j+k]):
diff+=1
if(diff>1):
break
res+=diff
return res