-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathEditDistance.java
More file actions
54 lines (43 loc) · 1.67 KB
/
Copy pathEditDistance.java
File metadata and controls
54 lines (43 loc) · 1.67 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
// Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.
// You have the following 3 operations permitted on a word:
// 1. Insert a character
// 2. Delete a character
// 3. Replace a character
// See: https://leetcode.com/problems/edit-distance/
package leetcode.dynamic_programming;
import java.util.Arrays;
public class EditDistance {
public int minDistance(String word1, String word2) {
int[][] dp = new int[word1.length() + 1][word2.length() + 1];
for (int i = 0; i < dp.length; i++) {
dp[i][0] = i;
}
for (int i = 0; i < dp[0].length; i++) {
dp[0][i] = i;
}
for (int i = 1; i < dp.length; i++) {
for (int j = 1; j < dp[0].length; j++) {
if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1];
} else {
dp[i][j] = 1 + Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1]));
}
}
}
// printTable(dp);
return dp[word1.length()][word2.length()];
}
public static void main(String[] args) {
EditDistance sln = new EditDistance();
System.out.println(sln.minDistance("", "")); // 3
System.out.println(sln.minDistance("aba", "aba")); // 3
System.out.println(sln.minDistance("horse", "ros")); // 3
System.out.println(sln.minDistance("intention", "execution")); // 5
}
@SuppressWarnings("unused")
private void printTable(int[][] dp) {
for (int[] line : dp) {
System.out.println(Arrays.toString(line));
}
}
}