[leetcode] 72 Edit Distance

来源:互联网 发布:win10 mac美化 编辑:程序博客网 时间:2024/05/29 11:56

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

_________________________________________________________________

题目大致可以理解为字符串word1经过几步变化可以变为word2,添加、删除、调换均算一次操作

如:“abs”--->"kas" 就需要两步   abs-->bas-->kas

leetcode给的提示是动态规划,所以我们也就顺着这个思路写dp算法(其实之前自己想过分析两个string中相同字符的位置关系,不过似乎太复杂了点)

假设word1的长度为m,word2的长度为n,建立二位数据dp[m+ 1][n+ 1],dp[i][j]表示word1的前i位于word2的前j位的最短距离

dp[i][j]= min(  min(dp[i- 1][j], dp[i][j- 1])+ 1  ,        dp[i- 1][j- 1]+ flag  )              其中如果word1[i]和word2[j]相同则flag= 0,否则= 1;

class Solution {public:    int minDistance(string word1, string word2) {        int m= word1.length();        int n= word2.length();        if(m== 0) return n;        if(n== 0) return m;        vector<vector<int> >  dp(m+ 1, vector<int>(n+ 1, 0));        for(int i= 1; i< m+ 1; i++){            dp[i][0]= i;        }        for(int i= 1; i< n+ 1; i++){            dp[0][i]= i;        }                for(int i= 1; i< m+ 1; i++){            for(int j= 1; j< n+ 1; j++){                int flow= 0;                if(word1[i- 1]!= word2[j- 1])  flow= 1;                dp[i][j]= min(min(dp[i- 1][j], dp[i][j- 1])+ 1, dp[i- 1][j- 1]+ flow);            }        }                return dp[m][n];    }};




0 0