leetcode 72. Edit Distance

本文详细解析了LeetCode上的编辑距离问题,通过动态规划的方法给出了高效的求解算法。阐述了如何计算两个字符串之间的最小编辑操作次数,并提供了完整的Java实现代码。

leetcode 72. Edit Distance

Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (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

 

首先考虑如何简化问题,例如“ABC”和“DBA”如何算编辑距离。

先把问题简化为只有一个字符'A'和‘D'.那么只需要把A换为D就可以了。

然后看“A”和“DB”,需要把A更新B,然后在插入B,两步。   。。。

定义表达式D(i,j)。它表示从第1个字单词的第0位至第i位形成的子串和第2个单词的第0位至第j位形成的子串的编辑距离。

显然,

D(i,0) = i //删除i次变为空串

D(0,j) = j

状态转移方程是:

                                
D(i,j)=min           (      D(i-1, j)  + 1 //word1  (删除、新增、替换) 第i个字符 

             D(i, j-1)  + 1 )  //word2 (删除、新增、替换) 第j个字符

          D(i-1, j-1) + 1 //word1第i个字符和word2第 j个字符相等

          D(i-1,j-1) //word1第i个字符和word2第 j个字符相等

 

public class Solution {
    public int minDistance(String word1, String word2) {
       int len1=word1.length();
            int len2=word2.length();
            int [][] path=new int[len1+1][len2+1];

            for(int i=0;i<=len1;i++){
                path[i][0]=i;
            }
            for(int j=0;j<=len2;j++){
                path[0][j]=j;
            }
            for(int i=1;i<=len1;i++){
                for(int j=1;j<=len2;j++){
                    int temp;
                    if( word1.charAt(i-1)==word2.charAt(j-1))//i,j是path的下标,字符下表要-1
                        temp=path[i-1][j-1];
                    else
                        temp=1+path[i-1][j-1];
                    int temp2=Integer.min(path[i-1][j]+1,path[i][j-1]+1);
                    path[i][j]=Integer.min(temp2,temp);
                }
            }
            return path[len1][len2];
    }
}

 

转载于:https://www.cnblogs.com/sure0328/p/7111593.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值