C++ 程序实现莱文斯坦距离计算算法
两个字符串之间的莱文斯坦距离表示将一个字符串转换成另一个字符串所需的最小编辑次数,编辑操作包括插入、删除或替换单个字符。
**例如:**cat 和 mat 之间的莱文斯坦距离为 1 -
cat mat(substitution of ‘c’ with ‘m’)
下面是一个 C++ 程序,用于实现莱文斯坦距离计算算法。
算法
Begin Take the strings as input and also find their length. For i = 0 to l1 dist[0][i] = i For j = 0 to l2 dist[j][0] = j For j=1 to l1 For i=1 to l2 if(s1[i-1] == s2[j-1]) track= 0 else track = 1 done t = MIN((dist[i-1][j]+1),(dist[i][j-1]+1)) dist[i][j] = MIN(t,(dist[i-1][j-1]+track)) Done Done Print the Levinstein distance: dist[l2][l1] End
示例
#include <iostream>
#include <math.h>
#include <string.h>
using namespace std;
#define MIN(x,y) ((x) < (y) ? (x) : (y)) //calculate minimum between two values
int main() {
int i,j,l1,l2,t,track;
int dist[50][50];
//take the strings as input
char s1[] = "tutorials";
char s2[] = "point";
//stores the lenght of strings s1 and s2
l1 = strlen(s1);
l2= strlen(s2);
for(i=0;i<=l1;i++) {
dist[0][i] = i;
}
for(j=0;j<=l2;j++) {
dist[j][0] = j;
}
for (j=1;j<=l1;j++) {
for(i=1;i<=l2;i++) {
if(s1[i-1] == s2[j-1]) {
track= 0;
} else {
track = 1;
}
t = MIN((dist[i-1][j]+1),(dist[i][j-1]+1));
dist[i][j] = MIN(t,(dist[i-1][j-1]+track));
}
}
cout<<"The Levinstein distance is:"<<dist[l2][l1];
return 0;
}输出
The Levinstein distance is:8
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP