Edit Distance即编辑距离,衡量两个字符串的相似度的方法,详细可以搜索维基百科,核心思想是计算一个字符串要通过多少次的“插入、删除、替换”字符操作转变成另一字符串。
Java实现如下:
package ruc.database.similarity;
public class EditDistance {
public static int dynamicProgramming(String source, String target)
{
int ed=0;
//预处理字符串
//source=source.toLowerCase(); //case sensitive
//target=target.toLowerCase();
//声明并初始化变量
int sLength=source.length();
int tLength=target.length();
int[][] table=new int[sLength+1][tLength+1];
for(int i=0;i<=sLength;i++)
table[i][0]=i;
for(int i=0;i<=tLength;i++)
table[0][i]=i;
//实际计算
if(sLength==0) //source长度为0
ed=tLength;
else
{
if(tLength==0) //target长度为0
ed=sLength;
else
{
int cost=0;
for(int i=1;i<=sLength;i++)
for(int j=1;j<=tLength;j++)
{
if(source.charAt(i-1)==target.charAt(j-1))
cost=0;
else
cost=1;
table[i][j]=Math.min(table[i-1][j-1]+cost, table[i][j-1]+1);
table[i][j]=Math.min(table[i][j],table[i-1][j]+1);
}
ed=table[sLength][tLength];
}
}
return ed;
}
}