# # 【LeetCode】718. Maximum Length of Repeated Subarray 解题报告（Python）

## # 题目描述：

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

## # 解题方法

``````  3 1 2
1 0 1 0
2 0 0 2
2 0 0 1
``````

``````class Solution:
def findLength(self, A, B):
"""
:type A: List[int]
:type B: List[int]
:rtype: int
"""
m, n = len(A), len(B)
dp = [[0 for j in range(n + 1)] for i in range(m + 1)]
max_len = 0
for i in range(m + 1):
for j in range(n + 1):
if i == 0 or j == 0:
dp[i][j] = 0
elif A[i - 1] == B[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
max_len = max(max_len, dp[i][j])
return max_len
``````

``````class Solution:
def findLength(self, A, B):
"""
:type A: List[int]
:type B: List[int]
:rtype: int
"""
m, n = len(A), len(B)
dp = [[0 for j in range(n)] for i in range(m)]
max_len = 0
for i in range(m):
for j in range(n):
if A[i] == B[j]:
if i == 0 or j == 0:
dp[i][j] = 1
else:
dp[i][j] = dp[i - 1][j - 1] + 1
max_len = max(max_len, dp[i][j])
return max_len
``````

## # 日期

2018 年 9 月 11 日 ———— 天好阴啊