72. Edit Distance 两个单词的编辑距离

class Solution {
public:
    int minDistance(string word1, string word2) {
        if(word1 == word2) return 0;
        int m = word1.size(), n = word2.size();
        if(0 == m) return n;
        if(0 == n) return m;
        vector>difs(m+1, vector(n+1, 0));

        for(int i = 1; i <= m; ++i) difs[i][0] = i;
        for(int j = 1; j <= n; ++j) difs[0][j] = j;
        for(int i = 1; i <= m; ++i){
            for(int j = 1; j <= n; ++j){
                difs[i][j] = min(difs[i-1][j] + 1, min(difs[i][j-1] + 1, difs[i-1][j-1] + (word1[i-1]==word2[j-1]? 0 : 1)));
            }
        }
        return difs[m][n];
    }
};

你可能感兴趣的:(LeetCode)