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

二、思路

采用动态规划求编辑距离。

先给出编辑距离的定义:设A和B是2个字符串,要用最少的字符操作将字符串A转换为字符串B。这里所说的字符操作包括:

       (1)删除一个字符(delete);

       (2)插入一个字符(insert);

       (3)将一个字符改为另一个字符(substitute)。

将字符串A变换为字符串B所用的最少字符操作数称为字符串A到B的编辑距离(edit distance)。

动态规划递归式为:

               如果i=0且j=0        edit(0, 0) = 1
        如果i=0且j>0        edit(0, j) = edit(0, j-1)+1
        如果i>0且j=0        edit(i, 0) = edit(i-1, 0)+1
        如果i>0且j>0        edit(i, j) = min(edit(i-1, j)+1, edit(i, j-1)+1, edit(i-1, j-1)+f(i, j) )
其中:edit(i,j)表示S中[0.... i]的子串si到T中[0....j]的子串tj的编辑距离。
      f(i,j)表示S中第i个字符s(i)转换到T中第j个字符s(j)所需要的操作次数,如果s(i)==s(j),则不需要任何操作f(i, j)=0; 否则,需要替换操作,f(i, j)=1

三、代码

class Solution {
public:
    int minDistance(string word1, string word2) {
        int m = word1.size(), n = word2.size();
        if (m == 0) return n;
        if (n == 0) return m;
        int a[m + 1][n + 1];
        for(int i = 0; i <= m; ++i) a[i][0] = i;
        for(int j = 0; j <= n; ++j) a[0][j] = j;
        for(int i = 1; i <= m; ++i)
            for(int j = 1; j <= n; ++j){
                int f = (word1[i - 1] == word2[j - 1] ? 0 : 1);
                a[i][j] = min ( min ( a[i - 1][j] + 1, a[i][j - 1] + 1),a[i - 1][j - 1] + f);
            }
        return a[m][n];
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fullstack_lth

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值