Skip to content

Commit 1eb9a56

Browse files
author
pranav.date
committed
Add contributions for a pull request: Done (two new files added).
Ensure tests/build: Attempted but blocked due to missing Maven in this environment (reported).
1 parent 883a050 commit 1eb9a56

File tree

2 files changed

+76
-0
lines changed

2 files changed

+76
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package com.thealgorithms.strings;
2+
3+
/**
4+
* Computes the Levenshtein distance (edit distance) between two strings.
5+
* Time: O(n*m), Space: O(min(n, m)) if optimized, here using full DP for simplicity.
6+
*/
7+
public final class LevenshteinDistance {
8+
private LevenshteinDistance() {}
9+
10+
/**
11+
* Compute the edit distance between s and t.
12+
*
13+
* @param s first string (may be null)
14+
* @param t second string (may be null)
15+
* @return minimum number of single-character edits (insertions, deletions or substitutions)
16+
*/
17+
public static int compute(final String s, final String t) {
18+
if (s == null) return t == null ? 0 : t.length();
19+
if (t == null) return s.length();
20+
final int n = s.length();
21+
final int m = t.length();
22+
23+
if (n == 0) return m;
24+
if (m == 0) return n;
25+
26+
int[][] dp = new int[n + 1][m + 1];
27+
28+
for (int i = 0; i <= n; i++) dp[i][0] = i;
29+
for (int j = 0; j <= m; j++) dp[0][j] = j;
30+
31+
for (int i = 1; i <= n; i++) {
32+
char cs = s.charAt(i - 1);
33+
for (int j = 1; j <= m; j++) {
34+
char ct = t.charAt(j - 1);
35+
int cost = (cs == ct) ? 0 : 1;
36+
dp[i][j] = Math.min(Math.min(dp[i - 1][j] + 1, // deletion
37+
dp[i][j - 1] + 1), // insertion
38+
dp[i - 1][j - 1] + cost); // substitution
39+
}
40+
}
41+
42+
return dp[n][m];
43+
}
44+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package com.thealgorithms.strings;
2+
3+
import org.junit.jupiter.api.Test;
4+
import static org.assertj.core.api.Assertions.assertThat;
5+
6+
public class LevenshteinDistanceTest {
7+
8+
@Test
9+
void sameStringsHaveZeroDistance() {
10+
assertThat(LevenshteinDistance.compute("test", "test")).isZero();
11+
}
12+
13+
@Test
14+
void emptyToNonEmpty() {
15+
assertThat(LevenshteinDistance.compute("", "abc")).isEqualTo(3);
16+
assertThat(LevenshteinDistance.compute("abc", "")).isEqualTo(3);
17+
}
18+
19+
@Test
20+
void nullHandling() {
21+
assertThat(LevenshteinDistance.compute(null, null)).isZero();
22+
assertThat(LevenshteinDistance.compute(null, "abc")).isEqualTo(3);
23+
assertThat(LevenshteinDistance.compute("abc", null)).isEqualTo(3);
24+
}
25+
26+
@Test
27+
void typicalExamples() {
28+
assertThat(LevenshteinDistance.compute("kitten", "sitting")).isEqualTo(3);
29+
assertThat(LevenshteinDistance.compute("flaw", "lawn")).isEqualTo(2);
30+
assertThat(LevenshteinDistance.compute("gumbo", "gambol")).isEqualTo(2);
31+
}
32+
}

0 commit comments

Comments
 (0)