718. Maximum Length of Repeated Subarray
来源:互联网 发布:管碧玲 知乎 编辑:程序博客网 时间:2024/06/14 18:37
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
分析
令f[i][j]表示以A[i]、B[j]结尾的两个相同子数组的最大长度。容易得出状态转移方程如下
f[i][j]=0 if i==0 | j==0
f[i][j]=0 if A[i]!=B[i]
f[i][j]=1+f[i-1][j-1] if A[i]==B[j]
代码
class Solution {public: int findLength(vector<int>& A, vector<int>& B) { int length=0; int f[A.size()+1][B.size()+1]; for (int i = 0; i < A.size()+1; i++) f[i][0]=0; for (int j = 0; j < B.size()+1; j++) f[0][j]=0; for (int i = 1; i < A.size()+1; i++) for (int j = 1; j < B.size()+1; j++) { if (A[i-1]!=B[j-1]) { f[i][j]=0;} else {f[i][j]=f[i-1][j-1]+1;if (f[i][j] > length)length=f[i][j];}}return length; }};
阅读全文
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
- hdu 2544 最短路
- CentOS65安装Mysql5.7.20
- 基础练习 字母图形
- 轻松解决桌面或者开始菜单里的图标显示异常
- Kotlin学习(十七): 运算符重载
- 718. Maximum Length of Repeated Subarray
- 我们应该经常交流!
- MyBatis config 文件常用设置
- ACM
- Friends(老友记第一季词组)
- pip与wxpython的安装
- 20171119
- hihocoder1158 质数相关
- TensorFlow学习_note2