编辑距离

package com.yihaodian.mandy.keyword.server;



public class EidtDistance {

/*private String target;

public int n;

public void setTarget(String target) {
this.target = target;
this.n = target.length();
}*/

private static int minimum(int a,int b,int c){
int mi;
mi=a;
if(b<mi){
mi=b;
}
if(c<mi){
mi=c;
}
return mi;
}

public static int distance(String s,String t){
int d[][];
int n,m;
int i,j;
char s_i,t_j;
int cost;

n=s.length();
m=t.length();
if(n==0)
return m;
if(m==0)
return n;
d=new int[n+1][m+1];

for(i=0;i<=n;i++)
d[i][0]=i;
for(j=0;j<=m;j++)
d[0][j]=j;

for(i=1;i<=n;i++){
s_i=s.charAt(i-1);
for(j=1;j<=m;j++){
t_j=t.charAt(j-1);
if(s_i==t_j)
cost=0;
else
cost=1;
d[i][j]=minimum(d[i-1][j]+1, d[i][j-1]+1, d[i-1][j-1]+cost);
}
}
return d[n][m];
}

public static double getSimilarity(String target,String other){
int distance = distance(target, other);
int n=Math.max(target.length(), other.length());
return (n-distance)*1.0/n;
}

public static void main(String[] args) {
EidtDistance ed = new EidtDistance();
String str1 = "chenlb.blogjava.net";
String str2 = "chenlb.javaeye.com";
System.out.println("ld=" + ed.distance(str1, str2));
System.out.println("sim=" + ed.getSimilarity(str1, str2));


str1 = "sonyyy";
str2 = "sony";
System.out.println("ld2=" + ed.distance(str1, str2));
System.out.println("sim=" + ed.getSimilarity(str1, str2));

str1 = "leenovo";
str2 = "lenovo";
System.out.println("sim=" + EidtDistance.getSimilarity(str1, str2));

str1 = "adfahjfsd";
str2 = "adidas";
System.out.println("ld=" + ed.distance(str1, str2));
System.out.println("sim=" + ed.getSimilarity(str1, str2));

str1 = "cannon";
str2 = "canon";
System.out.println("sim=" + ed.getSimilarity(str1, str2));

str1 = "sony erricson";
str2 = "sony ericsson";
System.out.println("sim=" + ed.getSimilarity(str1, str2));

str1 = "erricson sony";
str2 = "sony ericsson";
System.out.println("sim=" + ed.getSimilarity(str1, str2));

}  
}

你可能感兴趣的:(编辑距离)