Levenshtein distance演算法:計算兩個字串的差異

來源:互聯網
上載者:User
 LEVENSHTEIN DISTANCE(LD)-計算兩字串相似性演算法


兩字串相似性計算方法有好多,現對基於編距的演算法的相似性計算自己總結下。

 

簡單介紹下Levenshtein Distance(LD):LD 可能衡量兩字串的相似性。它們的距離就是一個字串轉換成那一個字串過程中的添加、刪除、修改數值。


舉例:


如果str1="test",str2="test",那麼LD(str1,str2) = 0。沒有經過轉換。

如果str1="test",str2="tent",那麼LD(str1,str2) = 1。str1的"s"轉換"n",轉換了一個字元,所以是1。

如果它們的距離越大,說明它們越是不同。


Levenshtein distance最先是由俄國科學家Vladimir Levenshtein在1965年發明,用他的名字命名。不會拼讀,可以叫它edit distance(編輯距離)。


Levenshtein distance可以用來:


Spell checking(拼字檢查)

Speech recognition(語句識別)

DNA analysis(DNA分析)

Plagiarism detection(抄襲檢測)

LD用m*n的矩陣儲存距離值。演算法大概過程:


str1或str2的長度為0返回另一個字串的長度。

初始化(n+1)*(m+1)的矩陣d,並讓第一行和列的值從0開始增長。

掃描兩字串(n*m級的),如果:str1[i] == str2[j],用temp記錄它,為0。否則temp記為1。然後在矩陣d[i][j]賦於d[i-1][j]+1 、d[i][j-1]+1、d[i-1][j-1]+temp三者的最小值。

掃描完後,返回矩陣的最後一個值即d[n][m]

最後返回的是它們的距離。怎麼根據這個距離求出相似性呢?因為它們的最大距離就是兩字串長度的最大值。對字串不是很敏感。現我把相似性計算公式定為1-它們的距離/字串長度最大值。

 

   private Int32 levenshtein(String a, String b)
        {
 
            if (string.IsNullOrEmpty(a))
            {
                if (!string.IsNullOrEmpty(b))
                {
                    return b.Length;
                }
                return 0;
            }
 
            if (string.IsNullOrEmpty(b))
            {
                if (!string.IsNullOrEmpty(a))
                {
                    return a.Length;
                }
                return 0;
            }
 
            Int32 cost;
            Int32[,] d = new int[a.Length + 1, b.Length + 1];
            Int32 min1;
            Int32 min2;
            Int32 min3;
 
            for (Int32 i = 0; i <= d.GetUpperBound(0); i += 1)
            {
                d[i, 0] = i;
            }
 
            for (Int32 i = 0; i <= d.GetUpperBound(1); i += 1)
            {
                d[0, i] = i;
            }
 
            for (Int32 i = 1; i <= d.GetUpperBound(0); i += 1)
            {
                for (Int32 j = 1; j <= d.GetUpperBound(1); j += 1)
                {
                    cost = Convert.ToInt32(!(a[i-1] == b[j - 1]));
 
                    min1 = d[i - 1, j] + 1;
                    min2 = d[i, j - 1] + 1;
                    min3 = d[i - 1, j - 1] + cost;
                    d[i, j] = Math.Min(Math.Min(min1, min2), min3);
                }
            }
 
            return d[d.GetUpperBound(0), d.GetUpperBound(1)];
 
        }

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.