轉載自: https://blog.csdn.net/JavaReact/article/details/82144732

算法簡介:
Levenshtein Distance,又稱編輯距離,指的是兩個字符串之間,由一個轉換成另一個所需的最少編輯操作次數。
許可的編輯操作包括將一個字符替換成另一個字符,插入一個字符,刪除一個字符。
編輯距離的算法是首先由俄國科學家Levenshtein提出的,故又叫Levenshtein Distance。
-
/**
-
* 比較兩個字符串的相識度
-
* 核心算法:用一個二維數組記錄每個字符串是否相同,如果相同記為0,不相同記為1,每行每列相同個數累加
-
* 則數組最后一個數為不相同的總數,從而判斷這兩個字符的相識度
-
*
-
* @param str
-
* @param target
-
* @return
-
*/
-
private static int compare(String str, String target) {
-
int d[][]; // 矩陣
-
int n = str.length();
-
int m = target.length();
-
int i; // 遍歷str的
-
int j; // 遍歷target的
-
char ch1; // str的
-
char ch2; // target的
-
int temp; // 記錄相同字符,在某個矩陣位置值的增量,不是0就是1
-
if (n == 0) {
-
return m;
-
}
-
if (m == 0) {
-
return n;
-
}
-
d = new int[n + 1][m + 1];
-
// 初始化第一列
-
for (i = 0; i <= n; i++) {
-
d[i][ 0] = i;
-
}
-
// 初始化第一行
-
for (j = 0; j <= m; j++) {
-
d[ 0][j] = j;
-
}
-
for (i = 1; i <= n; i++) {
-
// 遍歷str
-
ch1 = str.charAt(i - 1);
-
// 去匹配target
-
for (j = 1; j <= m; j++) {
-
ch2 = target.charAt(j - 1);
-
if (ch1 == ch2 || ch1 == ch2 + 32 || ch1 + 32 == ch2) {
-
temp = 0;
-
} else {
-
temp = 1;
-
}
-
// 左邊+1,上邊+1, 左上角+temp取最小
-
d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + temp);
-
}
-
}
-
return d[n][m];
-
}
-
-
-
/**
-
* 獲取最小的值
-
*/
-
private static int min(int one, int two, int three) {
-
return (one = one < two ? one : two) < three ? one : three;
-
}
-
-
/**
-
* 獲取兩字符串的相似度
-
*/
-
public static float getSimilarityRatio(String str, String target) {
-
int max = Math.max(str.length(), target.length());
-
return 1 - (float) compare(str, target) / max;
-
}
-
public static void main(String[] args) {
-
String a= "Steel";
-
String b = "Steel Pipe";
-
System.out.println( "相似度:"+getSimilarityRatio(a,b));
-
}
算法原理:
該算法的解決是基於動態規划的思想,具體如下:
設 s 的長度為 n,t 的長度為 m。如果 n = 0,則返回 m 並退出;如果 m=0,則返回 n 並退出。否則構建一個數組 d[0..m, 0..n]。
將第0行初始化為 0..n,第0列初始化為0..m。
依次檢查 s 的每個字母(i=1..n)。
依次檢查 t 的每個字母(j=1..m)。
如果 s[i]=t[j],則 cost=0;如果 s[i]!=t[j],則 cost=1。將 d[i,j] 設置為以下三個值中的最小值:
緊鄰當前格上方的格的值加一,即 d[i-1,j]+1
緊鄰當前格左方的格的值加一,即 d[i,j-1]+1
當前格左上方的格的值加cost,即 d[i-1,j-1]+cost
重復3-6步直到循環結束。d[n,m]即為萊茵斯坦距離。
參考鏈接:
http://wdhdmx.iteye.com/blog/1343856
https://www.cnblogs.com/ymind/archive/2012/03/27/fast-memory-efficient-Levenshtein-algorithm.html
