动态规划(字符串编辑)--- 编辑距离

编辑距离

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')

题目描述:

  修改一个字符串成为另一个字符串,使得修改次数最少。一次修改操作包括:插入一个字符,删除一个字符,替换一个字符。

思路分析:

  动态规划思想,dp[i] [j]表示,将字符串word1的前i个字符化成字符串word2的前j个字符的最小修改次数。如果word1 的第i个字符和word2 的第j个字符相等那么 就不需要修改,dp[i] [j]=dp[i-1] [j-1]。如果不相等,那么dp[i] [j]=min(dp[i] [j-1],dp[i-1] [j],dp[i-1] [j-1])+1。

代码:

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];
}
posted @ 2019-07-02 16:56  yjxyy  阅读(818)  评论(0编辑  收藏  举报