718. Maximum Length of Repeated Subarray

Posted 小预备

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了718. Maximum Length of Repeated Subarray相关的知识,希望对你有一定的参考价值。

#week9

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

 

分析

   b  a  b

c  0  0  0

a  0  1  0

b  1  0  2

a  0  2  0

dp[i][j] = dp[i-1][j-1] + 1;

题解

 1 class Solution {
 2 public:
 3     int findLength(vector<int>& a, vector<int>& b) {
 4         int na = a.size(), nb= b.size();
 5         int dp[na+1][nb+1] = {};
 6         int mx = 0;
 7         for (int i = 1; i <= na; ++i) for (int j = 1; j <=nb; ++j) {
 8             if (a[i-1] == b[j-1]) dp[i][j] = dp[i-1][j-1] + 1;
 9             mx = max(mx,dp[i][j]);
10         }
11         
12         return mx;
13     }
14 };

 

以上是关于718. Maximum Length of Repeated Subarray的主要内容,如果未能解决你的问题,请参考以下文章

[leetcode] 718. Maximum Length of Repeated Subarray

LeetCode-718. Maximum Length of Repeated Subarray

LeetCode 718. 最长重复子数组(Maximum Length of Repeated Subarray)

718. Maximum Length of Repeated Subarray

Leetcode 718. Maximum Length of Repeated Subarray

LeetCode Maximum Length of Pair Chain