私はあいまい検索の実装に取り組んでおり、実装の一部として、Apache の StringUtils.getLevenshteinDistance を使用しています。現時点では、あいまい検索の特定の最大平均応答時間を目指しています。さまざまな機能強化といくつかのプロファイリングの後、最も時間が費やされる場所は、レーベンシュタイン距離の計算です。3 文字以上の検索文字列では、合計時間の約 80 ~ 90% を占めます。
さて、ここでできることにはいくつかの制限があることはわかっていますが、以前の SO の質問と LD のウィキペディアのリンクを読んだことがあります。しきい値を設定された最大距離に制限したい場合は、アルゴリズムに費やした時間ですが、これを正確に行う方法がわかりません。
距離がしきい値 k より小さい場合にのみ距離に関心がある場合は、マトリックスで幅 2k+1 の斜めストライプを計算するだけで十分です。このようにして、アルゴリズムは O(kl) 時間で実行できます。ここで、l は最短の文字列の長さです [3]。
以下に、StringUtils の元の LH コードを示します。後は私の改造です。基本的に、i,j 対角線から一定の長さの距離を計算しようとしています (したがって、私の例では、i,j 対角線の上下にある 2 つの対角線)。ただし、これは私が行ったので正しくありません。たとえば、最も高い対角線では、常に真上のセル値が選択されます。これは 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;
}