Minimum Edit Distance

解答:

 1 public class Solution {
 2     
 3     public static int minDistance(String word1, String word2) {
 4         int m = word1.length();
 5         int n = word2.length();
 6 
 7         int[][] dp = new int[m+1][n+1];
 8         for(int i = 0;i < m; i++) {
 9             dp[i][0] = i;
10         }
11 
12         for(int j = 0; j < n; j++) {
13             dp[0][j] = j;
14         }
15 
16         for(int i = 1; i < m; i++) {
17             for(int j = 1; j < n; j++) {
18                 if(word1.charAt(i-1) == word2.charAt(j-1)) {
19                     dp[i][j] = dp[i-1][j-1];
20                 } else {
21                     dp[i][j] = Math.min(Math.min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1])) + 1;
22                 }
23             }
24         }
25 
26         return dp[m][n];
27     }
28 
29     public static void main(String[] args) {
30         String word1 = "legend";
31         String word2 = "laland";
32 
33         int result = minDistance(word1, word2);
34 
35         System.out.println(result);
36     }
37 }

猜你喜欢

转载自www.cnblogs.com/wylwyl/p/10426619.html