edit-distance

来源:互联网 发布:李炎恢js视频教程下载 编辑:程序博客网 时间:2024/06/07 22:19

题目:

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) {        int m = word1.size();        int n = word2.size();        vector<vector<int> >dp(m+1,vector<int>(n+1));        for(int i = 0;i <= m ;i++){            for(int j = 0; j <= n ;j++){                if(i ==0){                    dp[i][j] = j;                }                else if(j ==0){                    dp[i][j] = i;                }                else{                    dp[i][j] = min(dp[i-1][j]+1,min(dp[i][j-1]+1,dp[i-1][j-1]+(word1[i-1]==word2[j-1]?0:1)));//删除,插入,替换操作的最小值                }            }        }        return dp[m][n];    }};

点评:

动态规划

假设给定的字符串是 SUNDAY 和 SATURDAY。如果 i= 2 , j = 4,即前缀字符串分别是SU和SATU(假定字符串索引从1开始)。这两个字串最右边的字符可以用三种不同的方式对齐:

1 (i, j): 对齐字符U和U。他们是相等的,没有修改的必要。我们仍然留下其中i = 1和j = 3,即问题E(1,3)

2 (i, -) : 对第一个字符串右对齐,第二字符串最右为空字符。我们需要一个删除(D)操作。我们还留下其中i = 1和j = 4的 子问题 E(i-1,j)。

3 (-, j) : 对第二个字符串右对齐,第一个字符串最右为空字符。在这里,我们需要一个插入(I)操作。我们还留下了子问题 i= 2 和 j = 3,E(i,j-1)。

对于这三种操作,我可以得到最少的操作为:

E(i, j) = min( [E(i-1, j) + D], [E(i, j-1) + I], [E(i-1, j-1) + R (如果 i,j 字符不一样)] )

到这里还没有做完。什么将是基本情况?

当两个字符串的大小为0,其操作距离为0。当其中一个字符串的长度是零,需要的操作距离就是另一个字符串的长度. 即:

E(0,0)= 0,E(i,0)= i,E(0,j)= j

原创粉丝点击