Concise DP Java Solution


  • 0
    J
        public int findLength(int[] A, int[] B) {
            int lenA = A.length, lenB = B.length;
            int[][] dp = new int[lenA][lenB];
            int max = 0;
            for (int i = 0; i < lenA; i++) {
                if (A[i] == B[0]) {
                  dp[i][0] = 1;
                }
            }
        
            for (int j = 0; j < lenB;j++) {
                if (A[0] == B[j]) {
                  dp[0][j] = 1;
                }
            }
        
            for (int i = 1; i < lenA; i++) {
                for (int j = 1; j < lenB; j++) {
                   if (A[i] == B[j]) {
                      dp[i][j] = dp[i - 1][j - 1] + 1;
                      max = Math.max(dp[i][j],max);
                   }
               }
            }
        
            return max;
         }

Log in to reply
 

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