Cet article décrit l'algorithme de similitude Java String. Partagez-le pour votre référence. La méthode de mise en œuvre spécifique est la suivante:
Copiez le code comme suit: classe publique Levenshtein {
private int compare (string str, string target) {
int d [] [];
int n = str.length ();
int m = cible.length ();
int i;
Int J;
char ch1;
char ch2; // cible
int temp;
if (n == 0) {
retour m;
}
if (m == 0) {
retour n;
}
d = new int [n + 1] [m + 1];
pour (i = 0; i <= n; i ++) {// Initialisez la première colonne
d [i] [0] = i;
}
pour (j = 0; j <= m; j ++) {// initialiser la première ligne
D [0] [J] = J;
}
pour (i = 1; i <= n; i ++) {// Traverse Str
ch1 = str.charat (i - 1);
// va faire correspondre la cible
pour (j = 1; j <= m; j ++) {
ch2 = cible.charat (j - 1);
if (ch1 == ch2) {
temp = 0;
} autre {
temp = 1;
}
// +1 à gauche, +1 en haut, + température dans le coin supérieur gauche pour prendre le minimum
d [i] [j] = min (d [i - 1] [j] + 1, d [i] [j - 1] + 1, d [i - 1] [j - 1] + temp);
}
}
retour d [n] [m];
}
privé int min (int one, int deux, int trois) {
retour (un = un <deux? un: deux) <trois?
}
/ **
* Obtenez la similitude de deux chaînes
*
* @param str
* Target @param
*
* @retour
* /
public float getsimilarityratio (string str, string target) {
return 1 - (float) comparer (str, cible) / 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 ("SimilityRatio =" + lt.getsimilarityRatio (Str, Target));
}
}
J'espère que cet article sera utile à la programmation Java de tous.