The Java string similarity algorithm is described in the example. Share to everyone for your reference. The implementation methods are as follows:
Copy Code 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's
Int J; Traversing Target's
Char ch1; STR's
Char CH2; Target's
int temp; Record the same character in increments of a matrix position value, 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 first row
D[0][J] = j;
}
for (i = 1; I <= n; i++) {//Traverse str
CH1 = Str.charat (i-1);
to match target.
for (j = 1; j <= M; j +) {
CH2 = Target.charat (j-1);
if (ch1 = = CH2) {
temp = 0;
} else {
temp = 1;
}
Left +1, top +1, upper left corner +temp min
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 help you with your Java programming.