DailyChallenge
718. 最长重复子数组
Medium
20200701
Description
给两个整数数组 A 和 B ,返回两个数组中公共的、长度最长的子数组的长度。
示例:
输入:
A: [1,2,3,2,1]
B: [3,2,1,4,7]
输出:3
解释:
长度最长的公共子数组是 [3, 2, 1] 。
提示:
❝
- 1 <= len(A), len(B) <= 1000 0 <= A[i], B[i] < 100
链接:https://leetcode-cn.com/problems/maximum-length-of-repeated-subarray
Solution
动态规划, dp[i][j] 以a的第i位,b的第j位为终点,a数组的前i为和b数组的前j位的公共子串长度位dp[i][j]
class Solution {
public int findLength(int[] A, int[] B) {
// dp[i][j] 以a的第i位,b的第j位为终点,a数组的前i为和b数组的前j位的公共子串长度位dp[i][j]
// 结果就是dp[i][j]的最大值
int a = A.length;
int b = B.length;
int[][] dp = new int[a + 2][b + 2];
int res = 0;
for(int i = 1; i <= a; i++){
for(int j = 1; j <= b; j++){
if(A[i - 1] == B[j - 1]){
dp[i][j] = dp[i - 1][j - 1] + 1;
res = Math.max(res, dp[i][j]);
}
}
}
return res;
}
}
❝我的公众号:GitKid
暂时每日分享LeetCode,我在不断学习的过程中,公众号也在不断充实,欢迎大家扫码关注。
TODO:动态规划专题
![0ca1929eccfe5a0a065d8ced318de15b.png](https://img-blog.csdnimg.cn/img_convert/0ca1929eccfe5a0a065d8ced318de15b.png)