Advertisement
Iam_Sandeep

72. Edit Distance Min operations to convert string 1 to another

Aug 1st, 2022 (edited)
1,329
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.13 KB | None | 0 0
  1. '''
  2. Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2.
  3.  
  4. You have the following three operations permitted on a word:
  5.  
  6. Insert a character
  7. Delete a character
  8. Replace a character
  9.  
  10.  
  11.  
  12. '''
  13.  
  14. class Solution:
  15.     def minDistance(self, word1: str, word2: str) -> int:
  16.         m=len(word1)
  17.         n=len(word2)
  18.         arr=[[None]*(n+1) for _ in range(m+1)]
  19.         def find(i,j):
  20.             op=float('inf')
  21.             if i==m and j==n:
  22.                 return 0
  23.             if i==m:
  24.                 return n-j
  25.             if j==n:
  26.                 return m-i
  27.             if arr[i][j]!=None:
  28.                 return arr[i][j]
  29.                
  30.             else:
  31.                 if word1[i]==word2[j]:
  32.                     op=min(op,find(i+1,j+1))
  33.                 else:
  34.                     #replace
  35.                     op=min(op,1+find(i+1,j+1))
  36.                     #delete
  37.                     op=min(op,1+find(i+1,j))
  38.                     #insert
  39.                     op=min(op,1+find(i,j+1))
  40.                 arr[i][j]=op
  41.                 return op
  42.         return find(0,0)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement