Skip to content

Commit 614d70f

Browse files
HARD/src/hard/EditDistance.java
1 parent 006854d commit 614d70f

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

HARD/src/hard/EditDistance.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package hard;
2+
3+
public class EditDistance {
4+
5+
public int minDistance(String word1, String word2) {
6+
int m = word1.length(), n = word2.length();
7+
if(m == 0) return n;
8+
if(n == 0) return m;
9+
10+
char[] str1 = word1.toCharArray();
11+
char[] str2 = word2.toCharArray();
12+
13+
int[][] table = new int[m+1][n+1];
14+
for(int i = 0; i < m+1; i++) table[i][0] = i;
15+
for(int j = 0; j < n+1; j++) table[0][j] = j;
16+
17+
for(int i = 1; i < m+1; i++){
18+
for(int j = 1; j < n+1; j++){
19+
int cost = 0;
20+
if(str1[i-1] != str2[j-1]) cost = 1;
21+
table[i][j] = Math.min(Math.min(table[i-1][j]+1, table[i][j-1]+1), table[i-1][j-1]+cost);
22+
}
23+
}
24+
25+
return table[m][n];
26+
}
27+
28+
}

0 commit comments

Comments
 (0)