C#通过编辑距离算法实现字符串相似度比较的代码

如下内容段是关于C#通过编辑距离算法实现字符串相似度比较的内容,希望能对各位有所帮助。

public class LevenshteinDistance
{

    private static LevenshteinDistance _instance=null;
    public static LevenshteinDistance Instance
    {
        get
        {
            if (_instance == null)
            {
                return new LevenshteinDistance();
            }
            return _instance;
        }
    }


    public int LowerOfThree(int first, int second, int third)
    {
        int min = first;
        if (second < min)
            min = second;
        if (third < min)
            min = third;
        return min;
    }

    public int Levenshtein_Distance(string str1, string str2)
    {
        int[,] Matrix;
        int n=str1.Length;
        int m=str2.Length;

        int temp = 0;
        char ch1;
        char ch2;
        int i = 0;
        int j = 0;
        if (n ==0)
        {
            return m;
        }
        if (m == 0)
        {

            return n;
        }
        Matrix=new int[n+1,m+1];

        for (i = 0; i <= n; i++)
        {
            Matrix[i,0] = i;
        }

        for (j = 0; j <= m; j++)
        {
            Matrix[0, j] = j;
        }

        for (i = 1; i <= n; i++)
        {
            ch1 = str1[i-1];
            for (j = 1; j <= m; j++)
            {
                ch2 = str2[j-1];
                if (ch1.Equals(ch2))
                {
                    temp = 0;
                }
                else
                {
                    temp = 1;
                }
                Matrix[i,j] = LowerOfThree(Matrix[i - 1,j] + 1, Matrix[i,j - 1] + 1, Matrix[i - 1,j - 1] + temp);


            }
        }

        for (i = 0; i <= n; i++)
        {
            for (j = 0; j <= m; j++)
            {
                Console.Write(" {0} ", Matrix[i, j]);
            }
            Console.WriteLine("");
        }
        return Matrix[n, m];

    }

    public decimal LevenshteinDistancePercent(string str1,string str2)
    {
        int maxLenth = str1.Length > str2.Length ? str1.Length : str2.Length;
        int val = Levenshtein_Distance(str1, str2);
        return 1 - (decimal)val / maxLenth;
    }
}

class Program
{


    static void Main(string[] args)
    {
        string str1 = "你好蒂蒂";
        string str2="你好蒂芬";
        Console.WriteLine("字符串1 {0}", str1);

        Console.WriteLine("字符串2 {0}", str2);

        Console.ReadLine();
    }
}
上一篇:Java设置session超时(失效)的三种方式


下一篇:JAVA笔记28-正则表达式(补充、不重要)