最近好久不写博客了,一直被动态规划狂虐
设A和B是2个字符串。要用最少的字符操作将字符串A转换为字符串B。这里所说的字符操作包括(1)删除一个字符; (2)插入一个字符; (3)将一个字符改为另一个字符。将字符串A变换为字符串B所用的最少字符操作数称为字符串A到 B的编辑距离,记为d(A,B)。对于给定的字符串A和字符串B,计算其编辑距离 d(A,B)。
例:fxpims xwrs
结果:4
代码如下:
public static int editDistant2(String a, String b) {
if (a == null || b == null) {
return -1;
}
int c[][] = new int[a.length()][b.length()];
for (int i = 0; i < a.length(); i++) {
for (int j = 0; j < b.length(); j++) {
//初始化01234567
if (i == 0) {
c[i][j] = j;
} else if (j == 0) {
c[i][j] = i;
//如果相等的话
}else if(a.charAt(i)==b.charAt(j)) {
c[i][j]=c[i-1][j-1];
}else {
c[i][j]=Math.min(c[i][j-1], Math.min(c[i-1][j], c[i-1][j-1]))+1;
}
}
}
for(int i=0;i<a.length();i++) {
for(int j=0;j<b.length();j++) {
System.out.print(" " + c[i][j]);
}
System.out.println();
}
return c[a.length()-1][b.length()-1];
}
思路如下表
x w r s
f 0 1 2 3
x 1 1 2 3
p 2 2 2 3
i 3 3 3 3
m 4 4 4 4
s 5 5 5 4