Wednesday, July 2, 2014

[Leetcode] Edit Distance

Problem 

Given two words S and T, find the minimum number of steps required to convert S to T. (each operation is counted as 1 step.) You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character

Algorithm

Let dp[i][j] be the minimum number of steps required to convert S.substring(0,i+1) to T.substring(0,j+1). The recurrence is 
dp[i][j]   =  Min(dp[i-1][j-1] ,                if S[i] = T[j]
                          dp[i][j-1]+1,                else insert at S[i] or delete at T[j]
                          dp[i-1][j]+1,                else delete S[i]    or  insert at T[j]
                          dp[i-1][j-1]+1)             else replace S[i] or T[j]

Code



No comments:

Post a Comment