Java String similarity algorithm _java

Source: Internet
Author: User
Tags first row

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.