718. Maximum Length of Repeated Subarray

Description

Given two integer arrays A and B, return the maximum length of an subarray that appears in both arrays.

Example 1:

Input:
A: [1,2,3,2,1]
B: [3,2,1,4,7]
Output: 3
Explanation:
The repeated subarray with maximum length is [3, 2, 1].

Note:

  1. 1 <= len(A), len(B) <= 1000
  2. 0 <= A[i], B[i] < 100

Solution

DP, time O(m * n), space O(m * n)

常规的DP题。

class Solution {
    public int findLength(int[] A, int[] B) {
        int m = A.length;
        int n = B.length;
        // dp[i + 1][j + 1] is the length of longest common subarray
        // ending with nums[i] and nums[j]
        int[][] dp = new int[m + 1][n + 1];
        int maxLen = 0;
        
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (A[i] != B[j]) {
                    continue;    
                }
                
                dp[i + 1][j + 1] = 1 + dp[i][j];
                maxLen = Math.max(maxLen, dp[i + 1][j + 1]);
            }
        }
        
        return maxLen;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容