72. Edit Distance

problem description

Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.

You have the following 3 operations permitted on a word:

  1. Insert a character

  2. Delete a character

  3. Replace a character

Example 1:

Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation: 
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')

Example 2:

Input: word1 = "intention", word2 = "execution"
Output: 5
Explanation: 
intention -> inention (remove 't')
inention -> enention (replace 'i' with 'e')
enention -> exention (replace 'n' with 'x')
exention -> exection (replace 'n' with 'c')
exection -> execution (insert 'u')

algorithm thought

字符串处理操作。之前也总结了字符串题目的几种方法。动态规划,字符串匹配的一些算法,字典树等等。如果看到题目找不到思路,没有做过类似的,就使用这几种方法试试。

这里两个字符串,使用动态规划处理。一个二维数组实现。首先说一下动态规划的状态转移方程如何理解。 要得到匹配horse,ros的最小次数。如果我们知道(horse,ro),(hors,ros),(hors,ro)三个字符串的匹配结果。

我们只需要判断,如果两个字符串当前index上两个字符相等,则(horse,ros)=(hors,ro) 如果两个字符不相等,则(horse,ros)=min((horse,ro),min((hors,ros),(hors,ro)))+1; 其中:(horse,ro)代表增加一个,(hors,ros)代表减少一个,(hors,ro)代表替换操作,我们使用二维数组解决此题。但是这题可以优化到只用一维数组,这里只给出一维数组的解答。

code

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

algorithm analysis

设word1 size = m,word2 size = n,最后时间复杂度O(m*n)

Last updated