【leetcode】72. Edit Distance 編輯距離計算

knzeus發表於2019-05-10

1. 題目

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

2. 思路

迭代遞推,用陣列mdi,表示對word1[0..i-1]和word2[0..j-1]的編輯距離。
則可以得到遞迴公式:
md[src, dst] = min{md[src, dst-1]+1, md[src-1, dst]+1, md[src-1, dst-1]+0 or 1 if [src] == [dst]}

3. 程式碼

class Solution {
public:
    // 插入、刪除、替換三種操作可以使用,要使得最後一個字元滿足,可以通過三種操作來完成,剩下的遞迴
    // md[src, dst] = min{md[src, dst-1]+1, md[src-1, dst]+1, md[src-1, dst-1]+0 or 1 if [src] == [dst]} 
    int minDistance(string word1, string word2) {
        int l1 = word1.length() + 1;
        int l2 = word2.length() + 1;
        int md[l1][l2];
        for (int j = 0; j < l2; j++) { md[0][j] = j; } // 插入
        for (int i = 0; i < l1; i++) { md[i][0] = i; } // 刪除
        for (int i = 1; i < l1; i++) {
            for (int j = 1; j < l2; j++) {
                md[i][j] = min(min(md[i-1][j]+1, md[i][j-1]+1), md[i-1][j-1] + (word1[i-1] == word2[j-1] ? 0 : 1));
            }
        }
        return md[l1-1][l2-1];
    }
};

相關文章