Edit Distance - LeetCode 72

題目描述:
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
Hide Tags Dynamic Programming String

分析:
繼續找遞推公式:
假設用dp[i][j]表示用word1中的前i個字符構成的子串與word2中前j個字符構成的子串之間的編輯距離,那麼很容易得到以下規律:
dp[i][0] = i; //表示將一個長度爲i字符串變爲空,那麼需要執行i次Relete操作。
dp[0][j] = j; //表示將一個空串轉換爲一個長度爲j的字符串,那麼需要執行j次Insert操作

若 word1[i]==word1[j],不用執行任何操作 那麼 dp[i][j] = dp[i-1][j-1]

否則 有三種可能:
    1)直接將 word1[i]換成word1[j],此時 dp[i][j] = dp[i-1][j-1] + 1
    2)直接將word1的前i個字符構成的子串轉換成word2的前j-1個字符構成的子串,編輯距離爲dp[i][j-1],然後再將word2[j]插入到word1最後,該情況下,dp[i][j] = dp[i][j-1] + 1;
    3) 直接將word1的前i-1個字符構成的子串轉換成word2的前j個字符構成的子串,編輯距離爲dp[i-1][j],然後再將word1[i]刪除,該情況下,dp[i][j] = dp[i-1][j] + 1;
因此當word1[i] != word1[j]時,dp[i][j] = min(dp[i-1][j-1],dp[i][j-1],dp[i-1][j]) +1;

以下是C++實現代碼,效率有待提高:

/**///////////////////////////////////48ms//*/
class Solution {
public:
    int min(int a,int b,int c){ //返回三個數中最小值
        int tmp = a < b ? a:b;
        return (tmp < c) ? tmp : c;
    }
    int minDistance(string word1, string word2) {
        int size1 = word1.size();
        int size2 = word2.size();
        if(size1 == 0 || size2 ==0) //若至少一個word的長度爲0,那麼返回兩者的長度之和
            return size1+size2;

        vector<vector<int>> dp(size1+1,vector<int>(size2+1,0)); //動態數組,
        //計算空串與非空串的編輯距離。由於動態數組中的下標表示子串的長度,因此下標範圍可以等於子串長度
        for(int j = 0; j <= size2; j++) 
            dp[0][j] = j; 
        for(int i = 0; i <= size1; i++)
            dp[i][0] = i;

        for(int i = 1; i <= size1; i++){
            for(int j = 1; j<= size2; j++){
                if(word1[i-1] == word2[j-1]){ //注意動態數組中的下標是子串的長度
                    dp[i][j] = dp[i-1][j-1];
                }else{
                    dp[i][j] = min(dp[i-1][j-1],dp[i-1][j],dp[i][j-1])+1; 
                }
            }
        }
        return dp[size1][size2];
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章