Edit Distance

Given two Strings, word1, word2. Find the distance of them. The distance is defined as the minimum steps to convert word1 to word2. In each step, there are three kind of operations can be perfromd:

add a character, delete a character and replace a character.

Solution:

1. We can use dynamic programming to solve this problem.

2. Notation:

dp[i][j] stands for the distance between w1[0..i-1] and w2[0..j-1].

3. Recursive Relations:

if w1[i-1] == w2[j-1]     dp[i][j] = dp[i-1][j-1]

e.g. w1 = abcd;  w2 = esd; i = 4, j = 3 -> w1[3]==w2[2] so we just need to calculate the distance between "abc" and "es"

if w1[i-1] != w2[j-1]      dp[i][j] = min{(dp[i-1][j-1]+1), (dp[i-1][j]+1), (dp[i][j-1])};

e.g. w1 = abcd; w2 = esa; i = 4, j = 3 -> w1[3]!=w2[2] we can do three operations on w1: replace, inset and delete

if we do replace: w1 -> abca and we just need to consider "abc" and "es" -> dp[i-1][j-1]

if we do insert: w1 -> abcda and we just need to consider "abcd" and "es" -> dp[i][j-1]

if we do delete: w1 -> abc and we just need to consider "abc" and "esa" -> dp[i-1][j]

and as we want the minimum one of these three and plus 1 which is the step of each operation.

Therefore:

dp[i][j] = w1[i-1]==w2[j-1]? dp[i-1][j-1] : min{dp[i-1][j-1], dp[i][j-1], dp[i-1][j]}+1;

4. Initialization:

dp[0][j] = j;

dp[i][0] = i;

5. finally we need dp[w1.length][w2.length]

Code:

public class Solution {
    public int minDistance(String word1, String word2) {
            int[][] dp = new int[word1.length()+1][word2.length()+1];
        for(int i = 0; i <= word1.length(); i++){
            dp[i][0] = i;
        }
        for(int i = 0; i <= word2.length(); i++){
            dp[0][i] = i;
        }
        for(int i = 0; i < word1.length(); i++){
            for(int j = 0; j < word2.length(); j++){
                if(word1.charAt(i)==word2.charAt(j))
                    dp[i+1][j+1]=dp[i][j];
                else{
                    int rep = dp[i][j]+1;
                    int add = dp[i+1][j]+1;
                    int dele = dp[i][j+1]+1;
                    dp[i+1][j+1]=Math.min(Math.min(rep, add), dele);
                }
            }
        }
        return dp[word1.length()][word2.length()];
    }
}
View Code

 

posted @ 2017-06-22 03:49  小风约定  阅读(86)  评论(0)    收藏  举报