[LeetCode] 718. Maximum Length of Repeated Subarray

[LeetCode] 718. Maximum Length of Repeated Subarray

题目描述

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 <= len(A), len(B) <= 1000
0 <= A[i], B[i] < 100

分析

当a[i] = b[j],如果i = 0 或者 j = 0, dp[i][j] = 1。如果i, j都不为0,那么dp[i][j] = dp[i-1][j-1]。返回最大的dp[i][j]。

class Solution {
public:
  int findLength(vector<int>& A, vector<int>& B) {
    int sizeA = A.size();
    int sizeB = B.size();
    vector<vector<int> > dp(sizeA + 1, vector<int>(sizeB + 1, 0));
    int res = 0;
    for (int i = 0; i < sizeA; i++) {
      for (int j = 0; j < sizeB; j++) {
        if (A[i] == B[j]) {
          if (i == 0 || j == 0) {
            dp[i][j] = 1;
          } else {
            dp[i][j] = dp[i - 1][j - 1] + 1;
            res = max(res, dp[i][j]);
          }
        }
      }
    }
    return res;
  }
};

猜你喜欢

转载自blog.csdn.net/weixin_39629939/article/details/78661090
今日推荐