LeetCode dynamic programming 72. Edit Distance

xiaoxiao2021-02-28  109

这周老师继续上周讲了动态规划,也提到了这个所谓的编辑距离,刚好在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

转载请注明原文地址: https://www.6miu.com/read-61743.html

最新回复(0)