My Java Solution Using DP


  • 0
    P
    public int minDistance(String word1, String word2) {
            int n = word1.length();
    	    int m = word2.length();
            if(n == 0)
                return m;
            if(m == 0)
                return n;
            int dp[][] = new int[n+1][m+1];
            for(int i = 1; i <= n; i++){
                for(int j = 1; j <= m; j++){
                    dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);
                    if(word1.charAt(i-1) == word2.charAt(j-1))
                        dp[i][j] = dp[i-1][j-1] + 1;
                } 
            }
            int val = dp[n][m];
            return word1.length() - val + word2.length() - val;
        }
    

Log in to reply
 

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