Dynamic Programming (String Editor) --- edit distance

Edit distance

72. Edit Distance (Hard)

Example 1:

Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation:
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')
Example 2:

Input: word1 = "intention", word2 = "execution"
Output: 5
Explanation:
intention -> inention (remove 't')
inention -> enention (replace 'i' with 'e')
enention -> exention (replace 'n' with 'x')
exention -> exection (replace 'n' with 'c')
exection -> execution (insert 'u')

Subject description:

  Modify a string to be another string, such that the minimum number of modifications. A modification operations include: insert a character, delete a character, replace a character.

Analysis of ideas:

  Dynamic programming, dp [i] [j] said it would before the i-th character string word1 minimum number of modifications into the first j characters of a string word2. If the i-th word1 word2 character and the j-th character are equal then no modification, dp [i] [j] = dp [i-1] [j-1]. If not equal, then dp [i] [j] = min (dp [i] [j-1], dp [i-1] [j], dp [i-1] [j-1]) + 1.

Code:

public int  minDistance(String word1,String word2){
    int m=word1.length();
    int n=word2.length();
    int [][]dp=new int [m+1][n+1];
    for(int i=0;i<=m;i++){
        dp[i][0]=i; //单纯的删除操作
    }
    for(int i=0;i<=n;i++){
        dp[0][i]=i; //单纯的插入操作
    }
    for(int i=0;i<m;i++){
        for(int j=0;j<n;j++){
            if(word1.charAt(i)==word2.charAt(j)){
                dp[i+1][j+1]=dp[i][j];
            }else{
                dp[i+1][j+1]=Math.min(dp[i][j+1],Math.min(dp[i+1][j],dp[i][j]))+1;
            }
        }
    }
    return dp[m][n];
}

Guess you like

Origin www.cnblogs.com/yjxyy/p/11121700.html