Leetcode Edit Distance

OpenSoucre發表於2014-07-04

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

輸入兩個單詞word1和word2,求出從word1轉換成word2的最少步驟。每個轉換操作算一步。轉換操作限定於:

  • 刪除一個字元
  • 插入一個字元
  • 替換一個字元

本題用動態規劃求解

設決策變數dp[i][j],表示從word[0..i-1]轉換為word2[0...j-1]的最少步驟

可以參考http://web.stanford.edu/class/cs124/lec/med.pdf

class Solution {
public:
    int minDistance(string word1, string word2) {
        int len1 =word1.length(), len2 = word2.length();
        if(len1 == 0) return len2;
        if(len2 == 0) return len1;
        if(word1 == word2) return 0;
        vector<vector<int> > dp(len1+1, vector<int>(len2+1,0));
        for(int i = 0; i <= len1; ++ i) dp[i][0] = i;
        for(int j = 0; j <= len2; ++ j) dp[0][j] = j;
        for(int i =1; i <= len1; ++ i){
            for(int j = 1; j <= len2; ++ j){
                dp[i][j] = min(dp[i-1][j-1]+(word1[i-1] != word2[j-1]? 1: 0),min(dp[i-1][j]+1, dp[i][j-1]+1));
            }
        }
        return dp[len1][len2];
    }
};

 

 

相關文章