Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
Advertisements