Skip to content

Commit b37bf8d

Browse files
committed
feat: distance_dp-java
1 parent c6d2776 commit b37bf8d

File tree

1 file changed

+27
-1
lines changed

1 file changed

+27
-1
lines changed

problems/为了绝杀编辑距离,卡尔做了三步铺垫.md

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,33 @@ else {
167167

168168

169169
Java:
170-
170+
```java
171+
class Solution {
172+
public int minDistance(String word1, String word2) {
173+
int m = word1.length();
174+
int n = word2.length();
175+
int[][] dp = new int[m+1][n+1];
176+
for(int i = 1; i <= m; i++){
177+
dp[i][0] = i;
178+
}
179+
for(int i = 1; i <= n; i++){
180+
dp[0][i] = i;
181+
}
182+
for(int i = 1; i <= m; i++){
183+
for(int j = 1; j <= n; j++){
184+
int left = dp[i][j-1]+1;
185+
int mid = dp[i-1][j-1];
186+
int right = dp[i-1][j]+1;
187+
if(word1.charAt(i-1) != word2.charAt(j-1)){
188+
mid ++;
189+
}
190+
dp[i][j] = Math.min(left,Math.min(mid,right));
191+
}
192+
}
193+
return dp[m][n];
194+
}
195+
}
196+
```
171197

172198
Python:
173199

0 commit comments

Comments
 (0)