/*
#author:zhuqi,2123419
#date:Dec 3,2014
#algorithm
#to produce the editdistance
#example:input:
str1=EXPONEN-TIAL
str2=--POLYNOMIAL
output:
editdistance=6
#example:input:
str1=S-NOWY
str2=SUNN-Y
output:
editdistance=3
#example:input:
str1=-SNOW-Y
str2=SUN--NY
output:
editdistance=5
*/
#include <iostream>
#include <string>
using namespace std;
int min(int a, int b)
{
return a < b ? a : b;
}
int EditDistance(string str1, string str2)
{
int max1 = str1.size();
int max2 = str2.size();
int edit[max1+1][max2+1];//edit[i][j]表示第一个字符串的长度i的子串到第二个字符串的长度为j的子串的编辑距离
/*分配存储空间 (数组分配也可以是动态的)
int **edit = new int*[max1 + 1];
for(int i = 0; i < max1 + 1 ;i++)
{
edit[i] = new int[max2 + 1];
}
*/
//1.初始化
for(int i = 0 ;i < max1 + 1 ;i++)
{
edit[i][0] = i;
}
for(int i = 0 ;i < max2 + 1;i++)
{
edit[0][i] = i;
}
//2.求编辑距离
for(int i = 1 ;i < max1 + 1 ;i++)
{
for(int j = 1 ;j< max2 + 1; j++)
{
int d;//当第一个字符串的第i个字符不等于第二个字符串的第j个字符时,d=1,否则d=0
int temp = min(edit[i-1][j] + 1, edit[i][j-1] + 1);//比较添加一个字符和删除一个字符的情况
if(str1[i-1] == str2[j-1])
{
d = 0 ;
}
else
{
d = 1 ;
}
edit[i][j] = min(temp, edit[i-1][j-1] + d);//将修改一个字符的情况和之前添加和删除较小的情况进行比较
}
}
//3.输出编辑距离情况
cout << "**************************************" << endl;
for(int i = 0 ;i < max1 + 1 ;i++)
{
for(int j = 0; j< max2 + 1; j++)
{
cout << edit[i][j] << " " ;
}
cout << endl;
}
cout << "**************************************" << endl;
int editdistance = edit[max1][max2];//edit[max1][max2]即为所求str1和str2的编辑距离
/*撤销存储空间
for(int i = 0; i < max1 + 1; i++)
{
delete[] edit[i];
edit[i] = NULL;
}
delete[] edit;
edit = NULL;
*/
return editdistance;
}
int main()
{
string str1;
string str2;
cout<<">>>Find The Editdistance<<<"<<endl;
cout<<"Please input str1 :"<<endl;
cin>>str1;
cout<<"Please input str2 :"<<endl;
cin>>str2;
int editdistance = EditDistance(str1, str2);
cout << "The editdistance is : " << editdistance << endl;
return 0;
}编辑距离
最新推荐文章于 2026-06-19 09:59:05 发布

1458

被折叠的 条评论
为什么被折叠?



