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)];
}