package csdn;
//两个字符串的编辑距离
/**
* 寻找 i j 的最小编辑距离
* 即可以从 [i-1,j-1] [i-1,j] [i,j-1]中的最小编辑距离找 正好对应修改 删除 插入
* 因为 最小值 才能得到最小值 套娃的思想
* 转移方程
* 初始值
* d[0][0]=0;d[0][j]=j; d[i][0]=i;
* 方程:
* d[i][j]=min(d[i-1][j-1]+temp,d[i-1][j]+1,d[i][j-1]+1);
* temp是标志位 if i j 相等 temp=0 else 不相等 temp=1
*
*/
import java.security.PrivilegedAction;
public class sanshiliu {
private int[][] d;
private char[] x;
private char[] y;
public sanshiliu(char[] x,char[] y){
this.d=new int[x.length+1][y.length+1];
this.x=x;
this.y=y;
}
//初始状态值
private void init(){
for (int i = 1; i <= x.length; i++) {
d[i][0]=i;
}
for (int i = 1; i <= y.length; i++) {
d[0][i]=i;
}
}
private void changeStatus(){
for (int i = 1; i <= x.length; i++) {
for (int j = 1; j <= y.length; j++) {
int temp=1;
if(x[i-1]==y[j-1]){
temp=0;
}
int z= Math.min(d[i-1][j-1]+temp, d[i-1][j]+1);
d[i][j]= Math.min(z, d[i][j-1]+1);
}
}
}
public static void main(String[] args) {
// String str1="abc";
// String str2="abd";
String str1="algorithm";
String str2="altruistic";
sanshiliu san=new sanshiliu(str1.toCharArray(), str2.toCharArray());
san.init();
san.changeStatus();
int[][] res= san.d;
for (int i = 0; i < res.length; i++) {
for (int j = 0; j < res[i].length; j++) {
System.out.print(res[i][j]+" ");
}
System.out.println();
}
}
}
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交