My AC Java DP solution, only use O(n) space.


  • 0
    H

    Very easy understand.

        public int minDistance(String word1, String word2) {
            int m = word1.length(), n = word2.length();
            int[] dp = new int[n + 1];
    
            for (int i = 0; i <= n; i++) dp[i] = i;
            for (int i = 1; i <= m; i++) {
                int prev = i;
                for (int j = 1; j <= n; j++) {
                    int cur;
                    if (word1.charAt(i - 1) == word2.charAt(j - 1))
                        cur = dp[j - 1];
                    else {
                        int insert = prev;
                        int delete = dp[j];
                        int replace = dp[j - 1];
                        cur = Math.min(Math.min(insert, delete), replace) + 1;
                    }
                    dp[j - 1] = prev;
                    prev = cur;
                }
                dp[n] = prev;
            }
    
            return dp[n];
        }
    

Log in to reply
 

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