Simple Java Accepted Solution, Pay attention to the initialization


  • 0
    P
    public class Solution {
        public int minDistance(String s, String t) {
            int m = s.length(), n = t.length();
            int[][] f = new int[m+1][n+1];
            for (int i = 1; i <= m; i++)
                Arrays.fill(f[i], Integer.MAX_VALUE);
            for (int i = 0; i <= n; i++)
                f[0][i] = i;
            for (int i = 0; i <= m; i++)
                f[i][0] = i;
            for (int i = 0; i < m; i++)
                for (int j = 0; j < n; j++)
                    if (s.charAt(i) == t.charAt(j))
                        f[i+1][j+1] = Math.min(f[i][j], f[i+1][j+1]);
                    else
                        f[i+1][j+1] = Math.min(Math.min(f[i][j]+1, Math.min(f[i+1][j]+1, f[i][j+1]+1)), f[i+1][j+1]);
            return f[m][n];
        }
    }

Log in to reply
 

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