動態(tài)規(guī)劃相似度算法經(jīng)常被用來確定兩個(gè)字符串文本是否相似,特別是在模糊匹配搜索中。下面封裝的C#.NET函數(shù)采用動態(tài)規(guī)劃法比較兩個(gè)短文本之間的相似度,返回百分比(精確道小數(shù)點(diǎn)兩位)。

private void button1_Click(object sender, EventArgs e)
{
this.textBox3.Text = "相似度:" + ComputeTextSame(this.textBox1.Text, this.textBox2.Text, false).ToString();
}
public static double ComputeTextSame(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));
}
該文章在 2025/2/24 14:43:16 編輯過