Java string similarity algorithm
- 2020-04-01 03:40:14
- OfStack
This article illustrates the Java string similarity algorithm. Share with you for your reference. The specific implementation method is as follows:
public class Levenshtein {
private int compare(String str, String target) {
int d[][]; //Matrix < br / >
int n = str.length();
int m = target.length();
int i; //Traverses the
of STR
int j; //Traverses the
of target
char ch1; //STR < br / >
char ch2; //The target of the < br / >
int temp; //Record the increment of the value of the same character at a 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++) { //Initializes the first column
d[i][0] = i;
}
for (j = 0; j <= m; j++) { //Initializes the first line
d[0][j] = j;
}
for (i = 1; i <= n; i++) { //Traverse the STR < br / >
ch1 = str.charAt(i - 1);
//To match the 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, and +temp on the top left is the smallest
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;
}
/**
* Gets the similarity between 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 has been helpful to your Java programming.