[Irving]字符串類似度-字符編輯距離算法(c#實現)

編輯距離(Edit Distance),又稱Levenshtein距離,是指兩個字串之間,由一個轉成另外一個所需的最少編輯操做次數。許可的編輯操做包括將一個字符替換成另外一個字符,插入一個字符,刪除一個字符。
例如將kitten一字轉成sitting:
sitten (k→s)
sittin (e→i)
sitting (→g)
俄羅斯科學家Vladimir Levenshtein在1965年提出這個概念。
 
 
原理再也不追溯,大牛博客應有盡有 善用搜索引擎皆可查詢,下面貼出C# 實現,經過.net 3.0 擴展方法 調用方便
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace System
{
   public static class StringExt
    {
        /// <summary>
        /// 獲取最小數值
        /// </summary>
        private static int getMin(int a, int b, int c)
        {
            var min = Math.Min(a, b);
            return Math.Min(min, c);
        }
        /// <summary>
        /// 字符距離算法,獲取字符編輯距離
        /// </summary>
        public static int Levenshtein_Distance(this string str1, string str2)
        {
            int[,] Matrix;
            int n = str1.Length;
            int m = str2.Length;
            char c1, c2;
            int temp = 0;
            int i, 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++)
            {
                c1 = str1[i - 1];
                for (j = 1; j <= m; j++)
                {
                    c2 = str2[j - 1];
                    if (c1.Equals(c2))
                    {
                        temp = 0;
                    }
                    else
                    {
                        temp = 1;
                    }
                    Matrix[i, j] = getMin(Matrix[i - 1, j] + 1, Matrix[i, j - 1] + 1, Matrix[i - 1, j - 1] + temp);

                }
            }



            return Matrix[n, m];
        }

       /// <summary>
       /// 獲取字符相識度
       /// </summary>
        public static decimal GetSimilarity(this string str1, string str2)
        {
            var l = str1.Levenshtein_Distance(str2);
           return  1 - (decimal)l / Math.Max(str1.Length, str1.Length);
        }

    }
}

 

調用方法算法

       //獲取字符編輯距離
            var l = textBox1.Text.ToString().Levenshtein_Distance(textBox2.Text);
            //獲取字符相識度
            decimal Similarity = textBox1.Text.GetSimilarity(textBox2.Text);
相關文章
相關標籤/搜索