leetcode 72. Edit Distance

来源:互联网 发布:转录组数据上传geo 编辑:程序博客网 时间:2024/06/06 09:22

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




分析:

类似求最长公共子序列。

两个字符串,判断他们之间的编辑距离,可以通过三个操作,删除,添加,替换。每种操作都算距离加一。例如“ab”和“abc”的距离为1.

动态规划:用dis[i][j]记录string1的前i个和string2的前j个的距离。那么可以知道:

1.如果str1的第i个,也就是str1[i-1]和str2的第j个也就是str2[j-1]相等的话,那么

dis[i][j] = dis[i-1][j-1]

2.如果str[i-1] != str2[j-1]

  2.1 通过替换操作把str[i-1]替换成str2[j-1],那么

    dis[i][j] = dis[i-1][j-1] + 1;

  2.2 通过插入操作在str1后面插入str2[j-1], 那么就相当于计算

    dis[i][j] = dis[i][j-1] + 1;

  2.3 通过插入操作在str2后面插入str1[i-1],那么就是

    dis[i][j] = dis[i-1][j] + 1;  

  在上述三个中选一个最小的。迭代更新。


ac代码:

class Solution {
public:
    int minDistance(string word1, string word2) {
        int i,j,L1=word1.length(),L2=word2.length();
        if(L1==0) return L2;
        if(L2==0) return L1;
        int dis[L1+1][L2+1];
        for(i=0;i<=L1;i++)
            dis[i][0]=i;
        for(j=0;j<=L2;j++)
            dis[0][j]=j;
        for(i=1;i<=L1;i++)
        {
            for(j=1;j<=L2;j++)
            {
                if(word1[i-1]!=word2[j-1])
                {
                    dis[i][j]=min(dis[i-1][j]+1,dis[i][j-1]+1);
                    dis[i][j]=min(dis[i-1][j-1]+1,dis[i][j]);
                }
                else
                {
                    dis[i][j]=dis[i-1][j-1];
                }
            }
        }
        return dis[L1][L2];
    }
};

0 0