相似度算法(编辑距离原理)

private float GetSimilar(String s1, String s2)
{
    if (s1 == s2)
        return 1;
    int n = s1.Length;
    int m = s2.Length;
    int i;
    int j;
    int[,] d = new int[n + 1, m + 1];//矩阵
    for (i = 0; i <= n; i++)
    {
        d[i, 0] = i;
    }
    for (j = 0; j <= m; j++)
    {
        d[0, j] = j;
    }
    char s_i;//字符串s1抽取的字符
    char t_j;//字符串s2抽取的字符
    int cost;//s_i和t_j是否相等的操作数
    for (i = 1; i <= n; i++)
    {
        s_i = s1[i - 1];
        for (j = 1; j <= m; j++)
        {
            t_j = s2[j - 1];
            if (s_i == t_j)
            {
                cost = 0;
            }
            else
            {
                cost = 1;
            }
            d[i, j] = Math.Min(Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1), d[i - 1, j - 1] + cost);
        }
    }
    return 1 - d[n, m] / (float)Math.Max(n, m);
}

你可能感兴趣的:(c#)