您的位置:首页 > 理论基础 > 计算机网络

字符串相似度计算的方法,使用SQL以及C#实现,本文非原创摘自网络(.NET SQL技术交流群入群206656202需注明博客园)

2014-05-24 11:36 881 查看
#region 计算字符串相似度
/// <summary>
/// 计算字符串相似度
/// </summary>
/// <param name="str1">字符串1</param>
/// <param name="str2">字符串2</param>
/// <returns>相似度</returns>
public static float Levenshtein(string str1, string str2)
{
//计算两个字符串的长度。
int len1 = str1.Length;
int len2 = str2.Length;
//比字符长度大一个空间
int[,] dif = new int[len1 + 1, len2 + 1];
//赋初值,步骤B。
for (int a = 0; a <= len1; a++)
{
dif[a, 0] = a;
}
for (int a = 0; a <= len2; a++)
{
dif[0, a] = a;
}
//计算两个字符是否一样,计算左上的值
int temp;
for (int i = 1; i <= len1; i++)
{
for (int j = 1; j <= len2; j++)
{
if (str1.Substring(i - 1, 1) == str2.Substring(j - 1, 1))
{
temp = 0;
}
else
{
temp = 1;
}
//取三个值中最小的
dif[i, j] = Min(dif[i - 1, j - 1] + temp, dif[i, j - 1] + 1, dif[i - 1, j] + 1);
}
}
return 1 - (float)dif[len1, len2] / Math.Max(str1.Length, str2.Length);
}
#endregion

//比较3个数字得到最小值
private static int Min(int i, int j, int k)
{
return i < j ? (i < k ? i : k) : (j < k ? j : k);
}


C#



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐