LeetCode 72. Edit Distance

3 篇文章 0 订阅
1 篇文章 0 订阅

题意:将字符串word1编辑成word2的操作步数,最小的操作步数称为edit distance(编辑距离),有三种操作:插入,删除,替换
You have the following 3 operations permitted on a word:

a) Insert a character
b) Delete a character
c) Replace a character
题解:《算法设计与分析》课程讲到的题,利用动态规划DP解决,建立距离矩阵,工作的就是填矩阵,时间复杂度O(mn),mn是字符串的长度。
dist[i][j]可能由三种状态转移得到:

// j = indexof word1    i = indexof word2

dist[i-1][j-1] -> dist[i][j]
如果word1[j-1] == word2[i-1] 那么直接得到,否则需要替换操作
dist[i-1][j] -> dist[i][j]
插入操作
dist[i][j-1] -> dist[i][j]
删除操作

算法开始,需要对第一行及第一列赋初值,初值代表插入删除操作直接得到word2
之后定义cost代表word1和word2对应位置的字符是否相等,相等则cost为0,又dist[i-1][j-1] -> dist[i][j] 只是新增了一个相同的字符,不需要进一步操作。
比较三个值,dist[i-1][j]+1 dist[i][j-1]+1 dist[i-1][j-1]+cost,较小者为编辑距离。得到的矩阵dist[i][j]值就是word1[1…j]编辑成word2[1….i]所需要的编辑距离。

public class Solution {
    public int minDistance(String word1, String word2) {
        //word1编辑成word2的编辑距离
        int len1 = word1.length();
        int len2 = word2.length();
        int[][] dist = new int[len2+1][len1+1];
        //第一列赋值为0
        for(int i = 0;i <= len2;i ++)
        {
            dist[i][0] = i;
        }
        for(int j = 0;j <= len1;j ++)
        {
            dist[0][j] = j;
        }
        int cost;
        for(int i = 1;i <= len2;i ++)
            for(int j = 1;j <= len1;j ++)
            {
                if(word1.charAt(j-1) == word2.charAt(i-1))
                    cost = 0;
                else cost = 1;
                dist[i][j] = Math.min(dist[i-1][j-1]+cost,Math.min(dist[i-1][j]+1,dist[i][j-1]+1));
            }
        return dist[len2][len1];
    }
}
//C++
class Solution {
private:
    vector<vector<int>> f;  
public:
    int minDistance(string word1, string word2) {
        int n, m, i, j;
        n = word1.length();
        m = word2.length();
        f.resize(n + 1);
        for (i=0; i<=n; i++) f[i].resize(m + 1);
        for (i=0; i<=n; i++) f[i][0] = i;
        for (i=0; i<=m; i++) f[0][i] = i;
        for (i=1; i<=n; i++)
            for (j=1; j<=m; j++)
                f[i][j] = min(min(f[i][j-1] + 1, f[i-1][j] + 1), f[i-1][j-1] + (word1[i-1] == word2[j-1] ? 0 : 1));
        return f[n][m];     
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值