C# 编辑距离实现

时间:2023-06-06 23:07:55
 /// <summary>
/// 计算
/// </summary>
/// <param name="str1"></param>
/// <param name="str2"></param>
public static decimal GoLevenshtein(string str1, string str2)
{
var len1 = str1.Length;
var len2 = str2.Length;
var dif = new int[len1 + ,len2 + ];
for (var a = ; a <= len1; a++)
{
dif[a,] = a;
}
for (var a = ; a <= len2; a++)
{
dif[,a] = a;
}
int temp; for (var i = ; i <= len1; i++)
{
for (var j = ; j <= len2; j++)
{
temp = str1[i - ] == str2[j - ] ? : ;
dif[i,j] = min(dif[i - ,j - ] + temp, dif[i,j - ] + ,dif[i - ,j] + );
}
} //计算相似度
var similarity = - (decimal)dif[len1,len2] / Math.Max(str1.Length, str2.Length);
return Math.Round(similarity,);
} //得到最小值
private static int min(int a,int b,int c)
{
return a<b?(a<c?a:c):(b<c?b:c);
}