我正在开发一个模糊搜索实现,作为实现的一部分,我们使用了Apache的StringUtils.getLevenshteinDistance。目前,我们为我们的模糊搜索设定了特定的最大平均响应时间。通过各种增强和一些分析,我们发现计算Levenshtein距离所花费的时间最多。对于长度为三个或更多字符的搜索字符串,它占据了总时间的大约80-90%。
现在,我知道在这里可以做的有限,但是我在以前的SO问题和LD的维基百科链接中读到过,如果愿意将阈值限制为设置的最大距离,那么可以帮助控制算法所花费的时间,但我不确定如何确切地做到这一点。
如果我们只对小于阈值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;
}