This article describes the Java string similarity algorithm. Share it for your reference. The specific implementation method is as follows:
Copy the code as follows: public class Levenshtein {
private int compare(String str, String target) {
int d[][]; // matrix
int n = str.length();
int m = target.length();
int i; // traversing str
int j; // traversal target
char ch1; // str
char ch2; // target
int temp; // Record the increment of the value at a certain matrix position, either 0 or 1
if (n == 0) {
return m;
}
if (m == 0) {
return n;
}
d = new int[n + 1][m + 1];
for (i = 0; i <= n; i++) { // Initialize the first column
d[i][0] = i;
}
for (j = 0; j <= m; j++) { // Initialize the first line
d[0][j] = j;
}
for (i = 1; i <= n; i++) { // traverse str
ch1 = str.charAt(i - 1);
// Go to match target
for (j = 1; j <= m; j++) {
ch2 = target.charAt(j - 1);
if (ch1 == ch2) {
temp = 0;
} else {
temp = 1;
}
// +1 on the left, +1 on the top, +temp on the upper left corner to take the minimum
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 int min(int one, int two, int three) {
return (one = one < two ? one : two) < three ? one : three;
}
/**
* Get the similarity of two strings
*
* @param str
* @param target
*
* @return
*/
public float getSimilarityRatio(String str, String target) {
return 1 - (float) compare(str, target) / Math.max(str.length(), target.length());
}
public static void main(String[] args) {
Levenshtein lt = new Levenshtein();
String str = "ab";
String target = "ac";
System.out.println("similarityRatio=" + lt.getSimilarityRatio(str, target));
}
}
I hope this article will be helpful to everyone's Java programming.