Repository navigation
Expand file tree
/
Copy pathLevenshtein.java
More file actions
70 lines (55 loc) · 1.97 KB
/
Copy pathLevenshtein.java
File metadata and controls
70 lines (55 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package algoexpert.medium;
/*
PROBLEM:
Find minimum number of edit operations needed on string1 to obtain string2
Operations | each with cost of 1
- insert
- delete
- substitution
EXAMPLE:
"abc"
"yabd"
-> 2 (insert y, substitute c with d)
LOGIC:
Calculate edit distance for each pair of substrings in matrix
to construct solution for strings
if (str1.charAt(row - 1) == str2.charAt(col - 1))
{ minDistance[row][col] = minDistance[row - 1][col - 1]; }
else
{ minDistance[row][col] = 1 + Math.min(minDistance[row - 1][col - 1], Math.min(minDistance[row][col - 1], minDistance[row - 1][col])); }
prev diagonal elem -> substitution -> current
prev row elem -> insert/delete -> current
prev col elem -> insert/delete -> current
SOLUTION:
1. DP - matrix of edit ops | time : O(nm) | space : O(nm)
*/
public class Levenshtein
{
public static void test()
{ System.out.println(levenshteinDistance("abc", "yabd"));}
public static int levenshteinDistance(String str1, String str2)
{
int[][] minDistance = new int[str1.length() + 1][str2.length() + 1];
for (int row = 1; row < minDistance.length; ++row)
{ minDistance[row][0] = minDistance[row - 1][0] + 1; }
for (int col = 1; col < minDistance[0].length; ++col)
{ minDistance[0][col] = minDistance[0][col - 1] + 1; }
for (int row = 1; row < minDistance.length; ++row)
{
for (int col = 1; col < minDistance[0].length; ++col)
{
if (str1.charAt(row - 1) == str2.charAt(col - 1))
{
minDistance[row][col] = minDistance[row - 1][col - 1];
}
else
{
minDistance[row][col] = 1 + Math.min(minDistance[row - 1][col - 1],
Math.min(minDistance[row][col - 1],
minDistance[row - 1][col]));
}
}
}
return minDistance[str1.length()][str2.length()];
}
}