转自:https://www.cnblogs.com/Katerina/p/11355153.html
编辑距离概念描述
编辑距离,又称Levenshtein距离,是指两个字串之间,由一个转成另一个所需的最少编辑操作次数。许可的编辑操作包括:1、将一个字符串替换成另一个字符,2、插入一个字符,3、删除一个字符。
例如将kitten转成sitting:
1.sitten (k->s)
2.sittin (e->i)
3.sitting (->g)
俄罗斯科学家Vladimir Levenshtein在1965年提出这个概念。
问题
找出字符串的编辑距离,即把一个字符串s1最少经过多少步操作变成编辑字符串s2,操作者由三种:添加一个字符,删除一个字符,修改一个字符
解析
首先定义这样一个函数–edit(i,j),它表示第一个字符串的长度为i的子串到第二个字符串的长度为j的字串的编辑距离。
显然可以由如下动态规划公示:
- if(i0)且(j0),edit(i,j)=0;
- if(i==0)且(j>0),edit(i,j)=j;
- if(i>0)且j==0,edit(i,j)=i;
- if(i>=1)且(j>=1),edit(i,j)==min{edit(i-1,j)+1,edit(i,j-1)+1,edit(i-1,j-1)+f(i,j)}; 当第一个字符串的第i个字符不等于第二个字符串的第j个字符时,f(i,j)=1;否则,f(i,j)=0.
0 | f | a | i | l | i | n | g | |
---|---|---|---|---|---|---|---|---|
0 | ||||||||
s | ||||||||
a | ||||||||
i | ||||||||
l | ||||||||
n |
0 | f | a | i | l | i | n | g | |
---|---|---|---|---|---|---|---|---|
0 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
s | 1 | |||||||
a | 2 | |||||||
i | 3 | |||||||
l | 4 | |||||||
n | 5 |
计算edit(1,1):
- edit(0,1)+1==2;
- edit(1,0)+1==2;
- edit(0,0)+f(1,1)0+11
- min(edit(0,1)+1,edit(1,0)+1,edit(0,0)+f(1,1))==1
- 因此edit(1,1)==1
依次类推:
0 | f | a | i | l | i | n | g | |
---|---|---|---|---|---|---|---|---|
0 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
s | 1 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
a | 2 | 2 | 1 | 2 | 3 | 4 | 5 | 6 |
i | 3 | 3 | 2 | 1 | 2 | 3 | 4 | 5 |
l | 4 | 4 | 3 | 2 | 1 | 2 | 3 | 4 |
n | 5 | 5 | 4 | 3 | 2 | 2 | 2 | 3 |
c++代码
#include<iostream>
#include<fstream>
#include<string>
#include <vector>
using namespace std;
#define STRINGMAXLEN 1024
int edit(string s1, string s2);
int min(int i,int j )
{
return i<j?i:j;
}
int main(int argc, char* argv[])
{
cout << "Please enter the first string:\n";
string s1;
getline(cin,s1);
cout <<"Please enter the second string: \n";
string s2;
getline(cin,s2);
int d=edit(s1,s2);
printf("the Edit Distance of %s and %s is: %d\n",s1,s2,d);
return 0;
}
int edit(string s1, string s2)
{
int maxLen1=s1.length();
int maxLen2=s2.length();
printf("maxLen1=%d,maxLen2=%d\n",maxLen1,maxLen2);
char a_s1[STRINGMAXLEN];
char a_s2[STRINGMAXLEN];
strcpy(a_s1+1,s1.c_str());//用到 c_str()函数
strcpy(a_s2+1,s2.c_str());//用到 c_str()函数
vector<vector<int> >dp;// (maxLen1+2,vector<int>(maxLen2+1));//定义二维数组dp[][],n行 m列
dp.resize(maxLen2+1);
for(int i=0;i<maxLen2+1;i++)
{
dp[i].resize(maxLen1+1);
}
for(int i=0;i<maxLen2+1;i++)
{
dp[i][0]=i;
}
for(int i=0;i<maxLen1+1;i++)
{
dp[0][i]=i;
}
for(int i=1;i<maxLen2+1;i++)
{
for(int j=1;j<maxLen1+1;j++)
{
int d;
int temp=min(dp[i-1][j]+1,dp[i][j-1]+1);
if(a_s2[i]==a_s1[j])
{
d=0;
}else{
d=1;
}
printf("a_s2[%d]=%c,a_s1[%d]=%c,",i,a_s2[i],j,a_s1[j]);
printf("d=%d\n",d);
dp[i][j]=min(temp,dp[i-1][j-1]+d);
}
}
printf("0 0 ");
for(int j=1;j<maxLen1+1;j++)
{
printf("%c ",a_s1[j]);
}
printf("\n");
for(int i=0;i<maxLen2+1;i++)
{
if(i>0)
{
printf("%c ",a_s2[i]);
}else{
printf("0 ");
}
for(int j=0;j<maxLen1+1;j++)
{
printf("%d ",dp[i][j]);
}
printf("\n");
}
int dis=dp[maxLen2][maxLen1];
return dis;
}