LeetCode dynamic programming 72. Edit Distance

本文深入讲解了编辑距离算法,这是一种衡量两个字符串相似度的方法。通过插入、删除或替换字符的操作,实现了从一个字符串转换到另一个字符串所需的最小步骤数计算。文章提供了详细的实现代码,并推荐了进一步学习的资源。

这周老师继续上周讲了动态规划,也提到了这个所谓的编辑距离,刚好在LeetCode上看到了就顺便练练手吧,没想到难度还是hard,不过让我自己想我估计肯定是想不出来的=.=

具体的算法细则以及证明可以看一下百度百科,我们老师上课讲的挺复杂了,画了好大一个图才讲完,虽然觉得没必要来写题解,但威力完成任务还是按照老规矩走一走流程吧。有兴趣的可以参考我们算法课的教材《算法导论》第162页,上面对这个讲得挺清楚的。

-------------------------下面是题目------------------------

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

题目没什么好说的,就是标准的编辑距离的概念

------------------------下面是代码----------------------

#include <string>
#include <iostream>
#include <memory.h>
using namespace std;
class Solution {
public:
    static int mi(int a,int b,int c)
	{
		if(a<=b&&a<=c)
		return a;
		else if(b<=a&&b<=c)
		return b;
		else
		return c;	
	}
    static int minDistance(string word1, string word2) {
        int l1=word1.length();
        int l2=word2.length();
        int e[1000][1000];
        memset(e,0,sizeof(e));
        for(int i=0;i<=l2;i++)
        e[i][0]=i;
        for(int i=0;i<=l1;i++)
        e[0][i]=i;
        for(int i=1;i<=l2;i++)
        for(int j=1;j<=l1;j++)
        {
        	int diff=1;
        	if(word1[j]==word2[i])
        	diff=0;
        	e[i][j]=mi(1+e[i-1][j],1+e[i][j-1],diff+e[i-1][j-1]);//状态转移方程
		}
		return e[l2][l1];
    }
};

其实对这个没什么好说的,主要就是那个状态转移方程,由于我们书上给我们讲过这个,也证明过,所以我就厚颜无耻的直接拿来用了。
------------------分割线----------------------

see you next illusion


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值