Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- LCS variation:
- for eg s1=heap s2=pea, for reaching from s1 to s2 we need to delete h & p from s1 because h is not in s2 and p is before the 'ea'
- so if you observer this you will realise you are converting s1-> LCS(s1,s2) ie. 'ea' and then coverting to the s2
- ok, now for converting s1-> LCA, you are doing deletions of ie. len(s1)-len(LCS) chars and then again you are doing
- addition of len(s2)-len(LCS) characters.
- so find the LCS length and deletions=len(s1)-len(LCS) and insertions=len(s2)-len(LCS) and total modificatoins=insertions+deletions
- '''
- def fun(s1,s2,n,m,dp):
- if n<0 or m<0:
- return 0
- if dp[n][m]!=-1:
- return dp[n][m]
- if s1[n]==s2[m]:
- dp[n][m]=1+fun(s1,s2,n-1,m-1,dp)
- else:
- dp[n][m]=max(fun(s1,s2,n-1,m,dp), fun(s1,s2,n,m-1,dp))
- return dp[n][m]
- class Solution:
- def minOperations(self, s1, s2):
- dp=[[-1]*len(s2) for _ in range(len(s1))]
- ans=fun(s1,s2,len(s1)-1,len(s2)-1,dp)
- deletions=len(s1)-ans
- insertions=len(s2)-ans
- return deletions+insertions
Advertisement
Add Comment
Please, Sign In to add comment