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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章