1. 程式人生 > >【LeetCode】128.Edit Distance

【LeetCode】128.Edit Distance

題目描述(Hard)

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:

  1. Insert a character
  2. Delete a character
  3. Replace a character

題目連結

https://leetcode.com/problems/edit-distance/description/

Example 1:

Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation: 
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')

Example 2:

Input: word1 = "intention", word2 = "execution"
Output: 5
Explanation: 
intention -> inention (remove 't')
inention -> enention (replace 'i' with 'e')
enention -> exention (replace 'n' with 'x')
exention -> exection (replace 'n' with 'c')
exection -> execution (insert 'u')

演算法分析

動態規劃法:設狀態為f[i][j] ,表示A[0,i-1] 和B[0,j-1] 之間的最小編輯距離。設A[0,i-1] 的形式是str1c,B[0,j-1] 的形式是str2d,
1. 如果 c==d,則f[i][j]=f[i-1][j-1] ;
2. 如果 c!=d,
(a) 如果將c 替換成d,則f[i][j]=f[i-1][j-1]+1;
(b) 如果在c 後面新增一個d,則f[i][j]=f[i][j-1]+1;
(c) 如果將c 刪除,則f[i][j]=f[i-1][j]+1;

提交程式碼:

class Solution {
public:
    int minDistance(string word1, string word2) {
        const int m = word1.size();
        const int n = word2.size();
        
        int f[m + 1][n + 1];
        
        for (int i = 0; i <= m; ++i) 
            f[i][0] = i;
        for (int j = 0; j <= n; ++j) 
            f[0][j] = j;
        
        for (int i = 1; i <= m; ++i) {
            for (int j = 1; j <= n; ++j) {
                if (word1[i - 1] == word2[j - 1])
                    f[i][j] = f[i - 1][j - 1];
                else {
                    // 刪除 or 新增
                    int dis = min(f[i][j - 1], f[i - 1][j]);
                    // 替換 or Others
                    f[i][j] = min(dis, f[i - 1][j - 1]) + 1;
                }
            }
        }
        
        return f[m][n];
    }
};