【发布时间】:2023-03-23 22:32:02
【问题描述】:
我已经编写了下面的算法来计算 Levenshtein 距离,它似乎根据我的测试返回了正确的结果。时间复杂度为O(n+m),空间为O(1)。
我所看到的所有现有算法都具有 O(n*m) 的空间复杂度,因为它们创建了一个矩阵。我的算法有问题吗?
public static int ComputeLevenshteinDistance(string word1, string word2)
{
var index1 = 0;
var index2 = 0;
var numDeletions = 0;
var numInsertions = 0;
var numSubs = 0;
while (index1 < word1.Length || index2 < word2.Length)
{
if (index1 == word1.Length)
{
// Insert word2[index2]
numInsertions++;
index2++;
}
else if (index2 == word2.Length)
{
// Delete word1[index1]
numDeletions++;
index1++;
}
else if (word1[index1] == word2[index2])
{
// No change as word1[index1] == word2[index2]
index1++;
index2++;
}
else if (index1 < word1.Length - 1 && word1[index1 + 1] == word2[index2])
{
// Delete word1[index1]
numDeletions++;
index1++;
}
else if (index2 < word2.Length - 1 && word1[index1] == word2[index2 + 1])
{
// Insert word2[index2]
numInsertions++;
index2++;
}
else
{
// Substitute word1[index1] for word2[index2]
numSubs++;
index1++;
index2++;
}
}
return numDeletions + numInsertions + numSubs;
}
【问题讨论】:
-
如果代码按预期工作,请考虑将其发布到codereview.stackexchange.com
-
同意,这听起来像是代码审查的问题
-
似乎给
"avarice"和"vase"提供了错误的结果... 应该是4(删除A,删除R,删除I,用S 代替C)但返回5。跨度> -
另一个测试用例:
"crevasse"和"vase"。返回 8,应该是 4 -
或者
"strange"和"rangers",返回7应该是4。
标签: c# algorithm distance levenshtein-distance