1. 程式人生 > >Leetcode題解:十幾行程式碼計算編輯距離

Leetcode題解:十幾行程式碼計算編輯距離

題目要求

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];
    }
};

在這裡插入圖片描述
滿意了滿意了