dp - 編輯距離

算法來源
     參考 : http://www.programcreek.com/2013/12/edit-distance-in-java/

編輯距離(Edit Distance),又稱Levenshtein距離,是指兩個字串之間,由一個轉成另一個所需的最少編輯操作次數。許可的編輯操作包括將一個字符替換成另一個字符,插入一個字符,刪除一個字符。一般來說,編輯距離越小,兩個串的相似度越大。

C++ 代碼: 

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int minDistance(string str1 ,string str2){
    const int len1 = str1.size();
    const int len2 = str2.size();

    int dp[len1+1][len2+1];
    for(int i =0;i<len1+1;i++){
        dp[i][0] = i;
    }
    for(int j =0;j<len2+1;j++){
        dp[0][j] = j;
    }
    for(int i = 0;i<len1;i++){
    	char a = str1.at(i);
    	for(int j = 0 ;j<len2 ;j++){
    	    char b = str2.at(j);
    	    if(a == b){
                dp[i+1][j+1] = dp[i][j];
    	    }else{
    		int replace = dp[i][j]+1;
    		int insert =  dp[i][j+1]+1;
    		int del = dp[i+1][j]+1;

    		int min = replace>insert ?insert:replace;
    		min =  min>del?del:min;
    		dp[i+1][j+1] = min;
    	    }
    	}
    }

    cout<<"**********矩陣************"<<endl;
    for(int i = 0;i<len1+1;i++){
      	for(int j = 0 ;j<len2+1 ;j++){
            cout<< dp[i][j] << " ";
      	}
        cout<<endl;
    }
    cout<<"************************"<<endl;
    return dp[len1][len2];
}

int main(int argc, char *argv[]){
    string s1 = "kitten";
    string s2 = "sitting";

    int distance = minDistance(s1 , s2);
    cout<< "編輯距離:" << distance <<endl;

    return 0;
}

結果:
**********矩陣************
0 1 2 3 4 5 6 7 
1 1 2 3 4 5 6 7 
2 2 1 2 3 4 5 6 
3 3 2 1 2 3 4 5 
4 4 3 2 1 2 3 4 
5 5 4 3 2 2 3 4 
6 6 5 4 3 3 2 3 
************************
編輯距離:3

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