8000 levenshtein algorithm · AllAlgorithms/java@b460f83 · GitHub
[go: up one dir, main page]

Skip to content
This repository was archived by the owner on Sep 7, 2025. It is now read-only.

Commit b460f83

Browse files
dafenixabranhe
authored andcommitted
levenshtein algorithm
1 parent 38b632d commit b460f83

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

strings/LevenshteinDistance.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// Source: https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Java
2+
public class LevenshteinDistance {
3+
private static int minimum(int a, int b, int c) {
4+
return Math.min(Math.min(a, b), c);
5+
}
6+
7+
8+
public static int computeLevenshteinDistance(CharSequence lhs, CharSequence rhs) {
9+
int[][] distance = new int[lhs.length() + 1][rhs.length() + 1];
10+
11+
for (int i = 0; i <= lhs.length(); i++)
12+
distance[i][0] = i;
13+
for (int j = 1; j <= rhs.length(); j++)
14+
distance[0][j] = j;
15+
16+
for (int i = 1; i <= lhs.length(); i++)
17+
for (int j = 1; j <= rhs.length(); j++)
18+
distance[i][j] = minimum(
19+
distance[i - 1][j] + 1,
20+
distance[i][j - 1] + 1,
21+
distance[i - 1][j - 1] + ((lhs.charAt(i - 1) == rhs.charAt(j - 1)) ? 0 : 1));
22+
23+
return distance[lhs.length()][rhs.length()];
24+
}
25+
// Driver method to test above
26+
public static void main(String args[]){
27+
System.out.println("Distance from 'stull' to 'still' is :"+ LevenshteinDistance.computeLevenshteinDistance("stull", "still"));
28+
System.out.println("Distance from 'stull' to 'steal' is :"+ LevenshteinDistance.computeLevenshteinDistance("stull", "steal"));
29+
System.out.println("Distance from 'skill' to 'steal' is :"+ LevenshteinDistance.computeLevenshteinDistance("skill", "steal"));
30+
}
31+
}

0 commit comments

Comments
 (0)
0