Edit Distance

Problem:
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
 Solution:
class Solution {
public:
    int minDistance(string word1, string word2) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int size1 = word1.size();
        int size2 = word2.size();
       
        int mat[size1 + 1][size2 + 1];
        mat[0][0] = 0;
        for (int i = 1; i < size2 + 1; i++)
            mat[0][i] = i;
           
        for (int i = 1; i < size1 + 1; i++)
            mat[i][0] = i;
      
        for (int i = 1; i < size1 + 1; i++) {
            for (int j = 1; j < size2 + 1; j++) {
                if (word1[i - 1] == word2[j - 1])
                    mat[i][j] = mat[i-1][j-1];
                else {
                    int min_del_ins = min(mat[i-1][j], mat[i][j-1]);
                    mat[i][j] = min(mat[i-1][j-1], min_del_ins) + 1;
                }
            }
        }
        return mat[size1][size2];
    }
};

No comments:

Post a Comment