张赐荣——一位视障程序员。
赐荣小站: www.prc.cx

張賜榮

张赐荣的技术博客

博客园 首页 新随笔 联系 订阅 管理

C# 采用动态规划算法,计算两个字符串之间的相似程度。

public static double CountTextSimilarity(string textX, string textY, bool isCase = false) // 计算文本相似度
{
if (textX.Length <= 0 || textY.Length <= 0)
{
return (0);
}
if (!isCase)
{
textX = textX.ToLower();
textY = textY.ToLower();
}
int[,] dp = new int[Math.Max(textX.Length, textY.Length) + 1, Math.Max(textX.Length, textY.Length) + 1];
for (int x = 0; x < textX.Length; x++)
{
for (int y = 0; y < textY.Length; y++)
{
if (textX[x] == textY[y])
{
dp[x + 1, y + 1] = dp[x, y] + 1;
}
else
{
dp[x + 1, y + 1] = Math.Max(dp[x, y + 1], dp[x + 1, y]);
}
}
}
return (Math.Round(((double)(dp[textX.Length, textY.Length]) / Math.Max(textX.Length, textY.Length)) * 100, 2));
}

posted on 2022-02-16 12:57  张赐荣  阅读(264)  评论(0编辑  收藏  举报

感谢访问张赐荣的技术分享博客!
博客地址:https://cnblogs.com/netlog/
知乎主页:https://www.zhihu.com/people/tzujung-chang
个人网站:https://prc.cx/