[leetcode] 72. Edit Distance 解题报告

题目链接:https://leetcode.com/problems/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


思路:本题是动态规划最长公共子串的变形,在比较两个word每一个位置时,有两种情况:

第一,计算w1[j] 到w2[i]的距离,如果w1[j] = w2[i], 则dp[i][j] = dp[i-1][j-1];

第二,如果w1[j]不等于w2[i], 则有三种操作可供选择:

1. 如果要删除w1[j]这个字符的话,则此时的距离为 dp[i][j-1] + 1;

2. 如果要替换w1[j]这个字符的话,则此时的距离为 dp[i-1][j-1] + 1;

2. 如果要在w1[j]之后添加一个字符的话,则此时的距离为 dp[i-1][j] + 1;

具体要选择哪种操作当然要看哪个代价最小,于是可以得出不相等情况下的状况转移方程为

dp[i][j] = min(dp[i][j-1] + 1, dp[i-1][j-1] + 1, dp[i-1][j] + 1);

这样就可以得出相等和不相等情况下的状态转移方程,在dp数组初始化的时候应该初始化如下

dp[i][0] = i;

dp[0][i] = i;

可以想象成如果另一个串为空,则转换成这个空串的距离.本题时间复杂度为O(M*N), 空间复杂度为O(M*N).

代码如下:

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

你可能感兴趣的:(leetcode,动态规划)