1. 程式人生 > 其它 >LeetCode 72 Edit Distance

LeetCode 72 Edit Distance

Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2.

You have the following three operations permitted on a word:

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

Solution

\(dp[i][j]\) 表示將 word1\([0,...,i)\) 轉變為 word2\([0,...,j)\)

的最小運算元。對於初始化,即考慮某一個串為空串,運算元自然為另一個非空串的長度:

\[dp[i][0] = i;dp[0][j] = j \]

現考慮轉移:假設現在已經知道了 \(dp[i][j]\) 之前的所有狀態最小運算元,如果 \(s1[i]==s2[j]\),則直接:

\[dp[i][j] = dp[i-1][j-1] \]

否則,則是考慮三個操作所帶來的花費:

  • 最簡單的就是 replace: \(dp[i][j] = dp[i-1][j-1]+1\)
  • 如果 \(s1[0,...,i-1) =s2[0,...,j)\),則直接 delete \(s[i-1]\):
\[dp[i][j] = dp[i-1][j]+1 \]
  • 如果 \(s1[0,...,i)+s2[j-1]=s2[0,...,j)\)
    ,則進行 insert:
\[dp[i][j] = dp[i][j-1]+1 \]
點選檢視程式碼
class Solution {
private:
    int dp[505][505];
public:
    int minDistance(string word1, string word2) {
        int n = word1.length(), m = word2.length();
        // dp[i][j]: word1[0,...,i) word2[0,...,j)
        for(int i=0;i<=n;i++)dp[i][0] = i;
        for(int i=0;i<=m;i++)dp[0][i] = i;
        for(int i=1;i<=n;i++){
            for(int j=1;j<=m;j++){
                if(word1[i-1]==word2[j-1])dp[i][j] = dp[i-1][j-1];
                else{
                    // word1[i-1]!=word2[j-1]
                    // dp[i-1][j-1] is known now
                    // Replace: dp[i][j] = dp[i-1][j-1]+1;
                    // Delete: dp[i][j] = dp[i-1][j]+1;
                    // Insert: dp[i][j] = dp[i][j-1]+1;
                    dp[i][j] = min(dp[i-1][j-1],min(dp[i-1][j],dp[i][j-1]))+1;
                }
            }
        }
        return dp[n][m];
    }
};