【发布时间】:2010-10-05 17:43:56
【问题描述】:
我正在研究模糊搜索实现,作为实现的一部分,我们使用了 Apache 的 StringUtils.getLevenshteinDistance。目前,我们正在为我们的模糊搜索设定一个特定的最大平均响应时间。经过各种增强和一些分析后,花费最多时间的地方是计算 Levenshtein 距离。搜索三个字母或更多字母的字符串大约占总时间的 80-90%。
现在,我知道这里可以做的事情有一些限制,但我已经阅读了以前的 SO 问题和 LD 的 Wikipedia 链接,如果有人愿意将阈值限制为设定的最大距离,那可能帮助减少花在算法上的时间,但我不确定如何准确地做到这一点。
如果我们只对 距离,如果它小于 a 阈值 k,则足以 计算宽度的对角线 矩阵中的 2k+1。这样, 算法可以在 O(kl) 时间内运行, 其中 l 是最短的长度 字符串。[3]
您将在下面看到来自 StringUtils 的原始 LH 代码。之后是我的修改。我试图基本上计算设定长度与 i,j 对角线的距离(因此,在我的示例中,i,j 对角线上方和下方的两个对角线)。但是,这不可能是正确的,因为我已经这样做了。例如,在最高的对角线上,它总是会选择正上方的单元格值,即 0。如果有人能告诉我如何按照我所描述的那样使这个函数起作用,或者关于如何使它如此的一些一般性建议, 这将不胜感激。
public static int getLevenshteinDistance(String s, String t) {
if (s == null || t == null) {
throw new IllegalArgumentException("Strings must not be null");
}
int n = s.length(); // length of s
int m = t.length(); // length of t
if (n == 0) {
return m;
} else if (m == 0) {
return n;
}
if (n > m) {
// swap the input strings to consume less memory
String tmp = s;
s = t;
t = tmp;
n = m;
m = t.length();
}
int p[] = new int[n+1]; //'previous' cost array, horizontally
int d[] = new int[n+1]; // cost array, horizontally
int _d[]; //placeholder to assist in swapping p and d
// indexes into strings s and t
int i; // iterates through s
int j; // iterates through t
char t_j; // jth character of t
int cost; // cost
for (i = 0; i<=n; i++) {
p[i] = i;
}
for (j = 1; j<=m; j++) {
t_j = t.charAt(j-1);
d[0] = j;
for (i=1; i<=n; i++) {
cost = s.charAt(i-1)==t_j ? 0 : 1;
// minimum of cell to the left+1, to the top+1, diagonally left and up +cost
d[i] = Math.min(Math.min(d[i-1]+1, p[i]+1), p[i-1]+cost);
}
// copy current distance counts to 'previous row' distance counts
_d = p;
p = d;
d = _d;
}
// our last action in the above loop was to switch d and p, so p now
// actually has the most recent cost counts
return p[n];
}
我的修改(仅限于 for 循环):
for (j = 1; j<=m; j++) {
t_j = t.charAt(j-1);
d[0] = j;
int k = Math.max(j-2, 1);
for (i = k; i <= Math.min(j+2, n); i++) {
cost = s.charAt(i-1)==t_j ? 0 : 1;
// minimum of cell to the left+1, to the top+1, diagonally left and up +cost
d[i] = Math.min(Math.min(d[i-1]+1, p[i]+1), p[i-1]+cost);
}
// copy current distance counts to 'previous row' distance counts
_d = p;
p = d;
d = _d;
}
【问题讨论】:
-
我突然想到我可以检查该值是否为零,然后忽略它或用任意高的值替换它。不过,可能应该多考虑一下。
标签: java algorithm performance levenshtein-distance