[leetcode] 72.Edit Distance

題目:
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
題意:
給定兩個字符串,找到字符串A變換到字符串B的最少步驟。
對一個字符串我們有三種操作,第一是插入一個字符,第二是刪除一個字符,第三是改變一個字符。
思路:
我們選取A的前i個字符變換到B的前j個字符。如果i==0,那麼必須插入j個字符,同理如果j==0的話,那麼A字符串刪除j個可以使兩者變成前j個相等。如果i,j不等於0的話,那麼有三種方式,已經知道A的前i-1個字符到j的方法,那麼在A中增加一個字符;如果已經知道A的前i-1個字符到達B的方法,那麼刪除A的第i個字符。如果知道A的前i-1個字符轉換到B的前j-1個字符的步驟,那麼我們可以通過更換A的第i個字符變成B的第j個字符。如果A的第i個字符跟B的第j個字符相等的話,那麼只需要知道A的前i-1個字符變換到B的前j-1個字符的步驟即可。
轉移方程是:

  • DP[i][j] = min(DP[i-1][j-1],min(DP[i-1][j],D[i][j-1])) +1
  • if(A[i-1] == B[j-1]) DP[i][j] = min(DP[i][j], DP[i-1][j-1])
    以上。
    代碼如下:
class Solution {
public:
    int minDistance(string word1, string word2) {
        if (word1.empty() || word2.empty())return (word1.empty()? word2.length() : word1.length());
        int len1 = word1.length();
        int len2 = word2.length();
        vector<vector<int>> DP(len1 + 1, vector<int>(len2 + 1, 0));
        for (int i = 0; i <= len1; i++)
        for (int j = 0; j <= len2; j++) {
            if (i == 0 || j == 0)DP[i][j] = ((i == 0) ? j : i);
            if (i != 0 && j != 0) {
                DP[i][j] = min(DP[i-1][j-1],min(DP[i - 1][j], DP[i][j - 1])) + 1;
                if(word1[i - 1] == word2[j - 1])DP[i][j] = min(DP[i][j], DP[i - 1][j - 1]);
            }
        }
        return DP[len1][len2];
    }
};
發佈了239 篇原創文章 · 獲贊 2 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章