计算编辑距离的算法

来源:互联网 发布:macbook 安装windows 编辑:程序博客网 时间:2024/05/01 11:00

         编辑距离,又称Levenshtein距离(也叫做Edit Distance),是指两个字串之间,由一个转成另一个所需的最少编辑操作次数。许可的编辑操作包括将一个字符替换成另一个字符,插入一个字符,删除一个字符。

        下面是用c++实现的该算法:

         文件:"Distance.h"

#ifndef DISTANCE_H#define DISTANCE_H#include <stdio.h>#include <string.h>#include <malloc.h>#include <stdlib.h>#define MAXSIZE 100class Distance{  public:    int LD (char const *s, char const *t);  private:    int Minimun(int a, int b, int c);}; #endif
      文件:”EditDistance.cpp“

      

/***Levenstain Distance** DP Formulation: LD(i, j) = min(LD(i-1,j)+1, LD(i,j-1)+1, LD(i-1,j-1)+(s[i-1]==t[j-1]?1:0) );** Time complexity : O(mn)   Space complexity : O(mn); */#include "Distance.h"int Distance::Minimun(int a, int b, int c){    int min;    min = a;    if(b < min){        min = b;    }    if(c < min){        min = c;    }    return min;}int Distance::LD(char const *s, char const *t){    int sLength, tLength;    int matrix[MAXSIZE][MAXSIZE];    int cost, upCost, leftCost, diaCost;    int s_c;//the value of a specific position in s;    int t_c;//the value of a specific position in t;    int result;    sLength = strlen(s);    tLength = strlen(t);    if(sLength==0){        return tLength;    }    else if(tLength==0){        return sLength;    }    for(int i=0; i<=sLength; i++){        matrix[0][i] = i;    }    for(int j=0; j<=tLength; j++){        matrix[j][0] = j;    }        for(int i=1; i<=sLength; i++){        s_c = s[i-1];        for(int j=1; j<=tLength; j++){            t_c = t[j-1];            if(t_c == s_c){                cost = 0;            }            else{                cost = 1;            }            upCost = matrix[j-1][i];            leftCost = matrix[j][i-1];            diaCost = matrix[j-1][i-1];            matrix[j][i] = Minimun(upCost+1, leftCost+1, diaCost+cost);        }    }    result = matrix[tLength][sLength];}int main(){    Distance d;    char s[10], t[10];    printf("Please input the strings to handle:\n");    scanf("%s", s);    fflush(stdin);    scanf("%s", t);    //char *s = "abcedf";    //char *t = "aabcdef";    int result;    result = d.LD(s, t);    printf("The Edit Distance of the two strings is %d.\n", result);        return 0;}



原创粉丝点击