您的位置:首页 > 其它

LEVENSHTEIN DISTANCE(LD)-计算两字符串相似度算法

2009-11-25 10:01 441 查看
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
[m]

最后返回的是它们的距离。怎么根据这个距离求出相似度呢?因为它们的最大距离就是两字符串长度的最大值。对字符串不是很敏感。现我把相似度计算公式定为1-它们的距离/字符串长度最大值。

C#源码

public class Distance {

/// <summary>

/// Compute Levenshtein distance

/// </summary>

/// <param name="s">String 1</param>

/// <param name="t">String 2</param>

/// <returns>Distance between the two strings.

/// The larger the number, the bigger the difference.

/// </returns>

public int LD (string s, string t) {

int n = s.Length; //length of s

int m = t.Length; //length of t

int[,] d = new int[n + 1, m + 1]; // matrix

int cost; // cost

// Step 1

if(n == 0) return m;

if(m == 0) return n;

// Step 2

for(int i = 0; i <= n; d[i, 0] = i++);

for(int j = 0; j <= m; d[0, j] = j++);

// Step 3

for(int i = 1; i <= n;i++) {

//Step 4

for(int j = 1; j <= m;j++) {

// Step 5

cost = (t.Substring(j - 1, 1) == s.Substring(i - 1, 1) ? 0 : 1);

// Step 6

d[i, j] = System.Math.Min(System.Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1),
d[i - 1, j - 1] + cost);

}

}

// Step 7

return d[n, m];

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: