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));
}
知乎: @张赐荣
赐荣博客: www.prc.cx