[LeetCode]718. Maximum Length of Repeated Subarray
来源:互联网 发布:2012觉醒知乎 编辑:程序博客网 时间:2024/06/07 07:45
- descrption
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) <= 10000 <= A[i], B[i] < 100
- 解题思路
求最长子串长度,利用动态规划算法。找到动态规划的状态和状态转移方程就可以解决问题。令C[i][j]表示以A[i]和b[j]结尾的最长字串长度,如果A[i]不等于B[j],那么C[i][j]就等于0,如果相等,那么C[i][j]就等于以A[i-1]和B[j-1]结尾的最长子串长度+1。
C[i][j] = A[i]==B[j]?C[i−1][j−1]+1:0
- 代码如下
class Solution {public: int findLength(vector<int>& A, vector<int>& B) { vector<vector<int>> C(A.size()+1, vector<int>(B.size()+1, 0)); int ans = 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]) { C[i][j] = C[i-1][j-1] + 1; } if(ans < C[i][j]){ ans = C[i][j]; } } } return ans; }};
原题地址
如有错误请指出,谢谢!
阅读全文
0 0
- Leetcode 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
- [LeetCode] 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)
- Leetcode | Maximum Length of Repeated Subarray
- LeetCode #718 Maximum Length of Repeated Subarray
- Leetcode | Maximum Length of Repeated Subarray
- LeetCode:Maximum Length of Repeated Subarray
- [leetcode]Maximum Length of Repeated Subarray
- [LeetCode]Maximum Length of Repeated Subarray
- Leetcode 718 Maximum Length of Repeated Subarray
- LeetCode:Maximum Length of Repeated Subarray
- leetCode-Maximum Length of Repeated Subarray
- LeetCode题解系列--718. Maximum Length of Repeated Subarray
- 数据结构实验之图论九:最小生成树
- 排列问题
- 一键部署java web应用(linux)
- 计算机组成原理:运算方法和运算器
- 数据结构实验之图论十:判断给定图是否存在合法拓扑序列
- [LeetCode]718. Maximum Length of Repeated Subarray
- 通过maven将多模块项目一键部署到Tomcat上
- Win10 64bit下安装GPU版Tensorflow+Keras
- 自学编程的六个技巧总结
- 数据结构实验之图论十一:AOE网上的关键路径
- 窗口事件
- 这3个UI设计细节,可以让你感受到和高手的差距
- C#设计模式——单例模式
- POJ 3304 (判断直线和线段的交)