Leetcode题解:十几行代码计算编辑距离

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jining11/article/details/83624520

题目要求

Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.
You have the following 3 operations permitted on a word:

  • Insert a character
  • Delete a character
  • Replace a character

求解思路

这是一个经典的动态规划问题了,以前做DNA序列比较时也完成过。

假设:

S 1 S 2 l 1 l 2 字符串S_1和S_2分别长为l_1和l_2
E i j S 1 i S 2 j E_{ij}代表S_1的前i个字符组成的串到S_2的前j个字符组成的串的最短编辑距离

状态转移方程:
E i j = m i n ( E i ( j 1 ) , E ( i 1 ) j , E ( i 1 ) ( j 1 ) + d i f f ( S 1 i , S 2 j ) ) E_{ij} =min(E_{i(j-1)}, E_{(i-1)j}, E_{(i-1)(j-1)}+diff(S_{1i}, S_{2j}))
d i f f ( x , y ) = { 0 x=y 1 x!=y diff(x, y)= \begin{cases} 0& \text{x=y}\\ 1& \text{x!=y} \end{cases}
状态初始化
E 0 j = j , j = 0... l 2 E_{0j} = j, j = 0...l_2
E i 0 = i , i = 0... l 1 E_{i0} = i, i = 0...l_1

源代码

有两点需要注意,一个是字符串的下标需要-1,另一个是diff的实现方式,如果写成我一开始提交的版本即int(word1[i-1]!=word2[j-1]),执行速度会非常之慢,还是写成(word1[i-1]!=word2[j-1] ? 1 : 0)为好

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

在这里插入图片描述
满意了满意了

猜你喜欢

转载自blog.csdn.net/jining11/article/details/83624520
今日推荐