718. Maximum Length of Repeated Subarray
来源:互联网 发布:sqlserver工程师培训 编辑:程序博客网 时间:2024/06/07 10:46
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: 3Explanation: The repeated subarray with maximum length is [3, 2, 1].
Note:
- 1 <= len(A), len(B) <= 1000
- 0 <= A[i], B[i] < 100
求两个数组的最长公共子数组的长度。类似LCS算法的实现,使用动态规划的方法。dp[i][j]保存A[0...i-1]和B[0...j-1]两个子数组的结尾部分的最长公共长度,求dp[i+1][j+1]时,已有dp[i][j]记录,如果A[i]==B[j],说明结尾公共部分又加多一个元素,则dp[i+1][j+1]=dp[i][j]+1,否则说明结尾无公共部分,dp[i+1][j+1]=0。两个数组的最长公共子数组的长度就是所有的dp[i][j]的最大值。
代码:
class Solution {public: int findLength(vector<int>& A, vector<int>& B) { int m = A.size(), n = B.size(), res = 0; vector<vector<int>> dp(m+1, vector<int>(n+1, 0)); for(int i = 1; i <= m; ++i) { for(int j = 1; j <= n; ++j) { dp[i][j] = (A[i-1] == B[j-1] ? dp[i-1][j-1]+1 : 0); res = max(res, dp[i][j]); } } return res; }};
不知不觉已经做了300题,但还是一条咸鱼。。
阅读全文
0 0
- Leetcode 718. Maximum Length of Repeated Subarray
- 718. Maximum Length of Repeated Subarray
- 718. Maximum Length of Repeated Subarray
- 718. Maximum Length of Repeated Subarray
- 718.Maximum Length of Repeated Subarray(M)
- 718. Maximum Length of Repeated Subarray
- 718. Maximum Length of Repeated Subarray
- 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
- 718. Maximum Length of Repeated Subarray
- 718. Maximum Length of Repeated Subarray
- 718. Maximum Length of Repeated Subarray
- 718. Maximum Length of Repeated Subarray
- 718. Maximum Length of Repeated Subarray
- [LeetCode] 718. Maximum Length of Repeated Subarray
- 【c#系列 三】从java到.net 高级
- js 去除空格、回车、换行
- Python之re方法
- equals的问题
- 11.15学习心得
- 718. Maximum Length of Repeated Subarray
- CentoS6.8安装Oracle
- Android 气泡碰撞
- js-DOM知识点
- Golang面试解析
- iOS输入框和button圆角问题
- 三、Python的输入输出
- Python编程:从入门到实践的动手试一试答案(第九章)
- 比较不同目录文件夹下同名文件的数量和显示同名文件名