-
Notifications
You must be signed in to change notification settings - Fork 20k
Refactor Levenshtein distance implementation #5138
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
vil02
merged 4 commits into
TheAlgorithms:master
from
sozelfist:ref/dp/levenshtein_distance
May 4, 2024
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
109 changes: 72 additions & 37 deletions
109
src/main/java/com/thealgorithms/dynamicprogramming/LevenshteinDistance.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,49 +1,84 @@ | ||
package com.thealgorithms.dynamicprogramming; | ||
|
||
import java.util.stream.IntStream; | ||
|
||
/** | ||
* @author Kshitij VERMA (github.com/kv19971) LEVENSHTEIN DISTANCE dyamic | ||
* programming implementation to show the difference between two strings | ||
* (https://en.wikipedia.org/wiki/Levenshtein_distance) | ||
* Provides functions to calculate the Levenshtein distance between two strings. | ||
* | ||
* The Levenshtein distance is a measure of the similarity between two strings by calculating the minimum number of single-character | ||
* edits (insertions, deletions, or substitutions) required to change one string into the other. | ||
*/ | ||
public class LevenshteinDistance { | ||
|
||
private static int minimum(int a, int b, int c) { | ||
if (a < b && a < c) { | ||
return a; | ||
} else if (b < a && b < c) { | ||
return b; | ||
} else { | ||
return c; | ||
} | ||
public final class LevenshteinDistance { | ||
private LevenshteinDistance() { | ||
} | ||
|
||
public static int calculateLevenshteinDistance(String str1, String str2) { | ||
int len1 = str1.length() + 1; | ||
int len2 = str2.length() + 1; | ||
int[][] distanceMat = new int[len1][len2]; | ||
for (int i = 0; i < len1; i++) { | ||
distanceMat[i][0] = i; | ||
} | ||
for (int j = 0; j < len2; j++) { | ||
distanceMat[0][j] = j; | ||
/** | ||
* Calculates the Levenshtein distance between two strings using a naive dynamic programming approach. | ||
* | ||
* This function computes the Levenshtein distance by constructing a dynamic programming matrix and iteratively filling it in. | ||
* It follows the standard top-to-bottom, left-to-right approach for filling in the matrix. | ||
* | ||
* @param string1 The first string. | ||
* @param string2 The second string. | ||
* @return The Levenshtein distance between the two input strings. | ||
* | ||
* Time complexity: O(nm), | ||
* Space complexity: O(nm), | ||
* | ||
* where n and m are lengths of `string1` and `string2`. | ||
* | ||
* Note that this implementation uses a straightforward dynamic programming approach without any space optimization. | ||
* It may consume more memory for larger input strings compared to the optimized version. | ||
*/ | ||
public static int naiveLevenshteinDistance(final String string1, final String string2) { | ||
int[][] distanceMatrix = IntStream.rangeClosed(0, string1.length()).mapToObj(i -> IntStream.rangeClosed(0, string2.length()).map(j -> (i == 0) ? j : (j == 0) ? i : 0).toArray()).toArray(int[][] ::new); | ||
|
||
IntStream.range(1, string1.length() + 1).forEach(i -> IntStream.range(1, string2.length() + 1).forEach(j -> { | ||
final int cost = (string1.charAt(i - 1) == string2.charAt(j - 1)) ? 0 : 1; | ||
distanceMatrix[i][j] = Math.min(distanceMatrix[i - 1][j - 1] + cost, Math.min(distanceMatrix[i][j - 1] + 1, distanceMatrix[i - 1][j] + 1)); | ||
})); | ||
|
||
return distanceMatrix[string1.length()][string2.length()]; | ||
} | ||
|
||
/** | ||
* Calculates the Levenshtein distance between two strings using an optimized dynamic programming approach. | ||
* | ||
* This edit distance is defined as 1 point per insertion, substitution, or deletion required to make the strings equal. | ||
* | ||
* @param string1 The first string. | ||
* @param string2 The second string. | ||
* @return The Levenshtein distance between the two input strings. | ||
* | ||
* Time complexity: O(nm), | ||
* Space complexity: O(n), | ||
* | ||
* where n and m are lengths of `string1` and `string2`. | ||
* | ||
* Note that this implementation utilizes an optimized dynamic programming approach, significantly reducing the space complexity from O(nm) to O(n), where n and m are the lengths of `string1` and `string2`. | ||
* | ||
* Additionally, it minimizes space usage by leveraging the shortest string horizontally and the longest string vertically in the computation matrix. | ||
*/ | ||
public static int optimizedLevenshteinDistance(final String string1, final String string2) { | ||
vil02 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if (string1.isEmpty()) { | ||
return string2.length(); | ||
} | ||
for (int i = 1; i < len1; i++) { | ||
for (int j = 1; j < len2; j++) { | ||
if (str1.charAt(i - 1) == str2.charAt(j - 1)) { | ||
distanceMat[i][j] = distanceMat[i - 1][j - 1]; | ||
} else { | ||
distanceMat[i][j] = 1 + minimum(distanceMat[i - 1][j], distanceMat[i - 1][j - 1], distanceMat[i][j - 1]); | ||
} | ||
|
||
int[] previousDistance = IntStream.rangeClosed(0, string1.length()).toArray(); | ||
|
||
for (int j = 1; j <= string2.length(); j++) { | ||
int prevSubstitutionCost = previousDistance[0]; | ||
previousDistance[0] = j; | ||
|
||
for (int i = 1; i <= string1.length(); i++) { | ||
final int deletionCost = previousDistance[i] + 1; | ||
final int insertionCost = previousDistance[i - 1] + 1; | ||
final int substitutionCost = (string1.charAt(i - 1) == string2.charAt(j - 1)) ? prevSubstitutionCost : prevSubstitutionCost + 1; | ||
prevSubstitutionCost = previousDistance[i]; | ||
previousDistance[i] = Math.min(deletionCost, Math.min(insertionCost, substitutionCost)); | ||
} | ||
} | ||
return distanceMat[len1 - 1][len2 - 1]; | ||
} | ||
|
||
public static void main(String[] args) { | ||
String str1 = ""; // enter your string here | ||
String str2 = ""; // enter your string here | ||
|
||
System.out.print("Levenshtein distance between " + str1 + " and " + str2 + " is: "); | ||
System.out.println(calculateLevenshteinDistance(str1, str2)); | ||
return previousDistance[string1.length()]; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.