forked from algorithm009-class01/algorithm009-class01
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinDistance.java
More file actions
30 lines (28 loc) · 955 Bytes
/
MinDistance.java
File metadata and controls
30 lines (28 loc) · 955 Bytes
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
package dynamic;
public class MinDistance {
public int minDistance(String word1,String word2){
int n1 = word1.length();
int n2 = word2.length();
int[][] dp = new int[n1+1][n2+1];
for (int j = 1; j <=n2 ; j++) {
dp[0][j] = dp[0][j-1] +1;
}
for (int i = 1; i <= n1; i++) {
dp[i][0] = dp[i-1][0] + 1;
}
for (int i = 1; i <=n1 ; i++) {
for (int j = 1; j <=n2 ; j++) {
if (word1.charAt(i-1) == word2.charAt(j-1)) dp[i][j] = dp[i-1][j-1];
else dp[i][j] = Math.min(Math.min(dp[i-1][j-1],dp[i][j-1]),dp[i-1][j])+1;
}
}
return dp[n1][n2];
}
public static void main(String[] args) {
String word1 = "horse";
String word2 = "ros";
MinDistance minDistance = new MinDistance();
int r = minDistance.minDistance(word1,word2);
System.out.println(r);
}
}