edit distance问题 leetcode72

class Solution {
public:
	
    int minDistance(string word1, string word2) {
    	int l1=word1.length();
    	int l2=word2.length();
    	int dp[l1+5][l2+5];
//    	memset(dp,0,sizeof(dp));
		for (int i=0;i<=l1;i++){
			for (int j=0;j<=l2;j++){
				if (i==0){
					dp[i][j]=j;
				}
				else if (j==0){
					dp[i][j]=i;
				}
				else dp[i][j]=1<<29;
			}
		}
//dp[0][0]=0;
    	for (int i=1;i<=l1;i++){
    		for (int j=1;j<=l2;j++){
    			if (word1[i-1]==word2[j-1]){
    				dp[i][j]=dp[i-1][j-1];
				}
				else {
					dp[i][j]=min(dp[i-1][j]+1,dp[i][j-1]+1);
					dp[i][j]=min(dp[i-1][j-1]+1,dp[i][j]);
				}
				//cout<<dp[i][j]<<" "<<dp[i-1][j]<<" "<<dp[i][j-1]<<" "<<dp[i-1][j-1]<<" *** ";
			//	cout<<dp[i][j]<<" ";
			}
			//cout<<endl;
		}
		return dp[l1][l2];
	}
};




上一篇文章我们讲了在机器学习中常用的距离度量方法,其中提到了edit distance,就是将一个字符串转化成另外一个字符串的最少步骤,包含replace,delete和insert三种方法。

自己尝试做了做,动态规划解法如下,和最长公共子序列问题思路差不多,贴一个讲的很清楚的


  1. dp[i][0] = i;
  2. dp[0][j] = j.

If they are euqal, then no more operation is needed and dp[i][j] = dp[i - 1][j - 1]. Well, what if they are not equal?

If they are not equal, we need to consider three cases:

  1. Replace word1[i - 1] by word2[j - 1] (dp[i][j] = dp[i - 1][j - 1] + 1 (for replacement));
  2. Delete word1[i - 1] and word1[0..i - 2] = word2[0..j - 1] (dp[i][j] = dp[i - 1][j] + 1 (for deletion));
  3. Insert word2[j - 1] to word1[0..i - 1] and word1[0..i - 1] + word2[j - 1] = word2[0..j - 1] (dp[i][j] = dp[i][j - 1] + 1 (for insertion)).

Putting these together, we now have:

  1. dp[i][0] = i;
  2. dp[0][j] = j;
  3. dp[i][j] = dp[i - 1][j - 1], if word1[i - 1] = word2[j - 1];
  4. dp[i][j] = min(dp[i - 1][j - 1] + 1, dp[i - 1][j] + 1, dp[i][j - 1] + 1), otherwise.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值