Java DP solution


  • 0
    Z
        public int minDistance(String word1, String word2) {
            int n1 = word1.length(), n2 = word2.length(), i, j;
            int[][] dp = new int[n1+1][n2+1];
            if (n1 == 0 || n2 == 0) {
                return n1 + n2;
            }
            
            dp[0][0] = 0;
            dp[0][1] = 0; dp[1][0] = 0;
            for (i=1;i<=n1;i++) {
                for (j=1;j<=n2;j++) {
                    if (word1.charAt(i-1) == word2.charAt(j-1)) {
                        dp[i][j] = dp[i-1][j-1] + 1;
                    } else {
                        dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);
                    }
                }
            }
            return n1 + n2 - 2*dp[n1][n2];
            
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.