Skip to content

Commit fb23242

Browse files
authored
Merge pull request #149 from qilingit/day31
Add Java solution for day31: Edit Distance
2 parents c0e9742 + 07b223d commit fb23242

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* Dynamic programming, operation of previous string plus one if the last character is not the same
3+
* XXXb -> YYYc => operation(XXX to YYY) + 1
4+
* XXXm -> XXXm => operation(XXX to YYY)
5+
*/
6+
class Solution {
7+
public int minDistance(String word1, String word2) {
8+
int m = word1.length(), n = word2.length();
9+
int dp[][] = new int[m+1][n+1];
10+
11+
/**
12+
* Construct a dp table
13+
* __|''|a|b|c|
14+
* ''| 0|1|2|3|...
15+
* ''| 0
16+
* d | 1
17+
* e | 2
18+
* f | 3
19+
*/
20+
for (int i = 0; i <= m; i++) {
21+
dp[i][0] = i;
22+
}
23+
24+
for (int j = 0; j <= n; j++) {
25+
dp[0][j] = j;
26+
}
27+
28+
for (int i = 0; i < m; i++) {
29+
for (int j = 0; j < n; j++) {
30+
char c1 = word1.charAt(i);
31+
char c2 = word2.charAt(j);
32+
33+
// If the last character is the same, we do nothing compare to previous string
34+
if (c1 == c2) {
35+
dp[i + 1][j + 1] = dp[i][j];
36+
} else {
37+
// we chose the minimum operation of three operation: insert, delete, replace
38+
dp[i + 1][j + 1] = Math.min(dp[i][j], Math.min(dp[i+1][j], dp[i][j+1])) + 1;
39+
}
40+
}
41+
}
42+
43+
return dp[m][n];
44+
}
45+
}

0 commit comments

Comments
 (0)