imashutosh51

edit distance

Mar 13th, 2026
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.64 KB | None | 0 0
  1. '''
  2. LCS variation:
  3. if the character matches, then look for next characters
  4. if the character doesn't match, there are 3 possibilties, given you can do all the operations on the s1 only:
  5.    insert: you can insert the mth of s2 character and then look for the next characters so insertion happened at n+1 with the mth character so n+1-1, m-1 ie (n,m-1)
  6.    delete: you can delete the nth character of s1 so after deletion indices (n-1,m) as the nth character you deleted and mth character will match with the remaining string
  7.    replace: you can replace the mth character with nth character so now nth and mth character mathcing, so you can move ahead and skip nth and mth character.
  8.  
  9.  
  10. Base case:
  11. if n<0-> it means s1 is finished so you will have to insert the remaining characters of the s2 to match ie. m+1
  12. if m<0-> it means s2 is finished so you will have to delete the reamining characters of the s1 to match ie. n+1
  13. '''
  14. def fun(s1,s2,n,m,dp):
  15.     if n<0: #s1 is finished so to match, we must insert m+1 char of s2 in beginning
  16.         return m+1
  17.     if m<0: #s2 is finished so to match, we must delete all n+1 character of s1 in the beginning
  18.         return n+1
  19.     if dp[n][m]!=-1:
  20.         return dp[n][m]
  21.    
  22.     if s1[n]==s2[m]:
  23.         dp[n][m]=fun(s1,s2,n-1,m-1,dp)
  24.     else:
  25.         insert=1+fun(s1,s2,n,m-1,dp)
  26.         delete=1+fun(s1,s2,n-1,m,dp)
  27.         replace=1+fun(s1,s2,n-1,m-1,dp)
  28.         dp[n][m]=min([insert,delete,replace])
  29.     return dp[n][m]
  30.  
  31. class Solution:
  32.     def minDistance(self, s1: str, s2: str) -> int:
  33.         dp=[[-1]*len(s2) for _ in range(len(s1))]
  34.         return fun(s1,s2,len(s1)-1,len(s2)-1,dp)
  35.        
Advertisement
Add Comment
Please, Sign In to add comment