Program to count substrings that differ by one character in Python


Suppose we have two strings s and t, we have to find the number of ways we can select a nonempty substring of s and replace one single character by another different character such that the resulting substring is one of the substring of t. We have to find the number of substrings that satisfy the condition above.

So, if the input is like s = "sts" t = "tsts", then the output will be 6 because the following are the pairs of substrings from s and t that differ by 1 character −

  • ("sts", "tsts"),
  • ("sts", "tsts"),
  • ("sts", "tsts"),
  • ("sts", "tsts"),
  • ("sts", "tsts"),
  • ("sts", "tsts")

The bold character portions are the substrings that are chosen from two strings s and t.

To solve this, we will follow these steps −

  • n1 := size of s
  • n2 := size of t
  • ans := 0
  • for each index i1 and character c1 from s, do
    • for each index i2, and character c2 from t, do
      • i := i1, j := i2
      • while i < n1 and j < n2 and s[i] is same as t[j], do
        • i := i + 1, j := j + 1
      • if i < n1 and j < n2 and s[i] is not same as t[j], then
        • := i + 1, j := j + 1
        • ans := ans + 1
        • while i < n1 and j < n2 and s[i] is same as t[j], do
          • i := i + 1, j := j + 1
          • ans := ans + 1
  • return ans

Example

Let us see the following implementation to get better understanding −

def solve(s, t):
   n1 = len(s)
   n2 = len(t)
   ans = 0

   for i1, c1 in enumerate(s):
      for i2, c2 in enumerate(t):
         i = i1
         j = i2

         while i < n1 and j < n2 and s[i] == t[j]:
            i += 1
            j += 1

         if i < n1 and j < n2 and s[i] != t[j]:
            i += 1
            j += 1
            ans += 1
            while i < n1 and j < n2 and s[i] == t[j]:
               i += 1
               j += 1
               ans += 1

   return ans

s = "sts"
t = "tsts"
print(solve(s, t))

Input

"sts", "tsts"

Output

6

Updated on: 05-Oct-2021

159 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements