【发布时间】:2020-01-15 22:47:20
【问题描述】:
什么是C#全模拟PHP函数similar_text()?
我试过这段代码
int ComputeLevenshteinDistance(string source, string target)
{
if ((source == null) || (target == null)) return 0;
if ((source.Length == 0) || (target.Length == 0)) return 0;
if (source == target) return source.Length;
int sourceWordCount = source.Length;
int targetWordCount = target.Length;
// Step 1
if (sourceWordCount == 0)
return targetWordCount;
if (targetWordCount == 0)
return sourceWordCount;
int[,] distance = new int[sourceWordCount + 1, targetWordCount + 1];
// Step 2
for (int i = 0; i <= sourceWordCount; distance[i, 0] = i++) ;
for (int j = 0; j <= targetWordCount; distance[0, j] = j++) ;
for (int i = 1; i <= sourceWordCount; i++)
{
for (int j = 1; j <= targetWordCount; j++)
{
// Step 3
int cost = (target[j - 1] == source[i - 1]) ? 0 : 1;
// Step 4
distance[i, j] = Math.Min(Math.Min(distance[i - 1, j] + 1, distance[i, j - 1] + 1), distance[i - 1, j - 1] + cost);
}
}
return distance[sourceWordCount, targetWordCount];
}
double CalculateSimilarity(string source, string target)
{
if ((source == null) || (target == null)) return 0.0;
if ((source.Length == 0) || (target.Length == 0)) return 0.0;
if (source == target) return 1.0;
int stepsToSame = ComputeLevenshteinDistance(source, target);
return (1.0 - ((double)stepsToSame / (double)Math.Max(source.Length, target.Length)));
}
结果值不是等价的php。
PHP Similar_text() function:计算两个strings 之间的相似度,如
编程经典:实现世界上最好的算法 奥利弗
(国际标准书号 0-131-00413-1)。
请注意,此实现不像 Oliver 的伪代码那样使用堆栈,而是递归调用,这可能会也可能不会加速整个过程。另请注意,该算法的复杂度为O(N**3),其中N 是最长字符串的长度。
【问题讨论】:
-
如何得到一个整数值,而不是序列?
-
您所要做的就是从
EditSequence中删除回溯跟踪。请看我的回答 -
对于 C#,soundex 算法有不同的实现。原始的 soundex 算法对英文文本效果最好,但对国际字符集的解释不够。因此,也许您想研究和重用现有的解决方案
标签: c# algorithm similarity