DP solution, same as finding longest common substring of two strings


  • 0

    Ending in position i and j, if A[i] == B[j] -> dp[i][j] = 1 + dp[i-1][j-1], else dp[i][j] = 0. Space can be optimized to O(1) with some trick, which I was not doing here.

        public int findLength(int[] A, int[] B) {
            if (A == null || B == null || A.length == 0 || B.length == 0) {
                return 0;
            }
            int len = 0, m = A.length, n = B.length;
            int[][] dp = new int[m+1][n+1];
            for (int i = 1; i <= m; i++) {
                for (int j = 1; j <= n; j++) {
                    if (A[i-1] == B[j - 1]) {
                        dp[i][j] = 1 + dp[i-1][j-1];
                        len = Math.max(len, dp[i][j]);
                    }
                }
            }
            return len;
        }
    

Log in to reply
 

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