Java 5 lines DP


  • 0
    Y

    In the following solution DP[i][j] denotes the longest common subsequence in s.substring(i) and t.substring(j)

    public int minDistance(String s, String t) {    
        int dp[][] = new int[s.length() + 1][t.length() + 1];
        for (int i = s.length() - 1; i >= 0; i--)
            for (int j = t.length() - 1; j >= 0; j--)
                dp[i][j] = s.charAt(i) == t.charAt(j) ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);                            
        return s.length() + t.length() - 2 * dp[0][0];
    }
    

Log in to reply
 

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