Syntax error Program to find minimum number of operations required to make one string substring of other in Python

Program to find minimum number of operations required to make one string substring of other in Python



Suppose we have two strings s and t, we have to find the minimum amount of operations required for s to make t a substring of s. Now, in each operation, we can choose any position in s and change the character at that position to any other character.

So, if the input is like s = "abbpqr", t = "bbxy", then the output will be 2, as we can take the substring "bbpq" and change 'p' to 'x' and 'q' to 'y'.

To solve this, we will follow these steps −

  • k := size of t, n := size of s
  • ans := 10^10
  • for i in range 0 to n - k, do
    • ss := substring of s[from index i to i+k-1]
    • ans := minimum of ans and number of unmatched character of s and t
  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, s, t):
      k, n = len(t), len(s)
      ans = 10**10
      for i in range(n - k + 1):
         ss = s[i:i+k]
         ans = min(ans, sum(ss[j]!=t[j] for j in range(k)))
      return ans
ob = Solution()
print(ob.solve("abbpqr", "bbxy"))

Input

"abbpqr", "bbxy"

Output

2
Updated on: 2020-10-05T07:24:52+05:30

686 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements