C# 计算两个字符的相似度

//计算相似度
        public static double LevenshteinDistanceSimilarty(string str1, string str2)
        {
            if (string.IsNullOrEmpty(str1) || string.IsNullOrEmpty(str2)) return 0;

            int str1Length = str1.Length;
            int str2Length = str2.Length;

            int[,] index = new int[str1Length, str2Length];

            if (str1Length == 0 || str2Length == 0) return 0;

            for (int i = 0; i < str1Length; i++)
            {
                for (int j = 0; j < str2Length; j++)
                {
                    int k = str1[i] == str2[j] ? 0 : 1;
                    if (i == 0 && j == 0) continue;
                    else if (i == 0)
                    {
                        index[i, j] = k + index[i, j - 1];
                        continue;
                    }
                    else if (j == 0)
                    {
                        index[i, j] = k + index[i - 1, j];
                        continue;
                    }
                    int temp = Min(index[i, j - 1],
                    index[i - 1, j],
                    index[i - 1, j - 1]);
                    index[i, j] = temp + k;
                }
            }
            double distance = index[str1Length - 1, str2Length - 1];
            double maxLength = str1Length > str2Length ? str1Length : str2Length;
            double similarty = 1 - (double)distance / maxLength;
            return similarty;
        }
        //交换比
        private static int Min(int a, int b, int c)
        {
            int temp = a < b ? a : b;
            temp = temp < c ? temp : c;
            return temp;
        }

  

C# 计算两个字符的相似度

上一篇:PostMan生成的测试报告 工具node.js、步骤、结果


下一篇:win10家庭版升级专业版的两种方法和密钥