【发布时间】:2018-04-30 01:23:42
【问题描述】:
我编写了这个算法来计算删除和插入(因此,编辑)数量的总和,以使第一个字符串等于第二个字符串。但它不起作用。
public static int distance (String s1, String s2) {
return distance(s1, s2, 0, 0);
}
private static int distance(String s1, String s2, int i, int j) {
if (i == s1.length) return j;
if (j == s2.length) return i;
if (s1.charAt(i) == s2.charAt(j))
return distance(s1, s2, i + 1, j + 1);
int rep = distance(s1, s2, i + 1, j + 1) + 1;
int del = distance(s1, s2, i, j + 1) + 1;
int ins = distance(s1, s2, i + 1, j) + 1;
return Math.min(del, Math.min(ins, rep));
}
编辑:示例 字符串 1:“casa” 字符串 2:“卡拉” edit_distance=2(1 次删除 + 1 次插入)
编辑2: 这些是有效的字符串: 字符串 1:“casa”,字符串 2:“cassa”,edit_distance=1; 字符串 1:“pioppo”,字符串 2:“pioppo”,edit_distance=0;
这些是不起作用的: 字符串 1:“casa”,字符串 2:“cara”,edit_distance=2; (在我的代码中=0) 字符串 1:“tassa”,字符串 2:“passato”,edit_distance=4; (在我的代码中=2)
【问题讨论】:
-
很高兴看到您正在尝试解决的问题的描述。
-
请添加一些您使用过的测试字符串示例及其输出。我们需要能够将应该发生的事情与正在发生的事情进行比较。可能导致问题的一件事(我不是可以运行代码的人)是长度为 1 的任意长度的字符串。您从 0 开始递归。
-
什么是代表?为什么以 1 为代价只在每个单词中跳过一个字母是可以的?似乎立即搞砸了您的示例并返回 1 而不是 2
-
我用一些例子编辑了这个问题
-
您的示例与您的代码不匹配。如果我只是运行你的代码,我会得到不同的数字。如果您不显示您的实际代码,我们无法告诉您您做错了什么。