码迷,mamicode.com
首页 > Windows程序 > 详细

C# 编辑距离实现

时间:2015-12-17 22:19:17      阅读:239      评论:0      收藏:0      [点我收藏+]

标签:

 /// <summary>
        /// 计算
        /// </summary>
        /// <param name="str1"></param>
        /// <param name="str2"></param>
        public static decimal GoLevenshtein(string str1, string str2)
        {
            var len1 = str1.Length;
            var len2 = str2.Length;
            var dif = new int[len1 + 1,len2 + 1];
            for (var a = 0; a <= len1; a++)
            {
                dif[a,0] = a;
            }
            for (var a = 0; a <= len2; a++)
            {
                dif[0,a] = a;
            }
            int temp;

            for (var i = 1; i <= len1; i++)
            {
                for (var j = 1; j <= len2; j++)
                {
                    temp = str1[i - 1] == str2[j - 1] ? 0 : 1;
                    dif[i,j] = min(dif[i - 1,j - 1] + temp, dif[i,j - 1] + 1,dif[i - 1,j] + 1);
                }
            }
          
            //计算相似度  
            var similarity = 1 - (decimal)dif[len1,len2] / Math.Max(str1.Length, str2.Length);
            return Math.Round(similarity,4);
        }

        //得到最小值  
        private static int min(int a,int b,int c)
        {
            return a<b?(a<c?a:c):(b<c?b:c);
        }

 

C# 编辑距离实现

标签:

原文地址:http://www.cnblogs.com/daxiongblog/p/5055282.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!