LeetCode_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

  

class Solution {
public:
    int minDistance(string word1, string word2) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int m = word1.size();
        int n = word2.size();
        vector<vector<int>>  table(m+1,vector<int>(n+1, 0));
         
        for(int i = 1; i <= n; i++) table[0][i] = i;
        for(int i = 1; i <= m; i++) table[i][0] = i;
        for(int i = 1; i <= m; i++)
            for(int j = 1; j <= n;j++)
            {
                int min1 = table[i-1][j] < table[i][j-1] ? table[i-1][j] : table[i][j-1];
                min1++;
                int min2 = word1[i-1] == word2[j-1] ? 0 : 1;
                min2 += table[i-1][j-1];
                table[i][j] = min1 < min2 ? min1 : min2;
            }
             
        return table[m][n];
    }
};

  reference :http://www.geeksforgeeks.org/dynamic-programming-set-5-edit-distance/

posted @   冰点猎手  阅读(222)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示