Maximum Length of Repeated Subarray
来源:互联网 发布:淘宝怎么搜店铺客服 编辑:程序博客网 时间:2024/05/29 17:21
问题来源
问题描述
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
问题分析
此题题意十分浅显,就是找出两个串中的最长的相同子串。一种比较蠢的方法就是逐一匹配,从A的第一个元素开始,每次遍历B,在B中找到相同元素就开始向后匹配。这种方法直接粗暴,但是时间复杂度较高,最差可以达到 O(n^3)。实际上此题是在动态规划的分类部分中找到的,也即是说,此题存在有动态规划的解法。实际上类似的题目有很多。在这里,我们令
dp[i][j]为 以A[i], B[j]结尾的相同子串的长度,
因此有 ,dp[i][j] = dp[i-1][j-1]
这里需要提醒的一点是,当 i = 0 或 j = 0时,上式显然不适用,此时有d[i][j] = 1
综上,我们有:
if A[i] == B[j] then dp[i][j] = dp[i-1][j-1]+1 // i > 0, j > 0 Or dp[i][j] = 1 // i = 0 || j = 0
解决代码
class Solution {public: int findLength(vector<int>& A, vector<int>& B) { vector<vector<int> > dp(A.size(), vector<int>(B.size(), 0)); int max = 0; for (auto i = 0; i < A.size(); i++) for (auto j = 0; j < B.size(); j++) { if (A[i] == B[j]) { if (i == 0 || j == 0) dp[i][j] = 1; else dp[i][j] = dp[i-1][j-1] + 1; max = max > dp[i][j] ? max : dp[i][j]; } } return max; }};
阅读全文
0 0
- Maximum Length of Repeated Subarray
- Maximum Length of Repeated Subarray
- 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
- 718. Maximum Length of Repeated Subarray
- LeetCode718. Maximum Length of Repeated Subarray(Medium)
- 718. Maximum Length of Repeated Subarray
- Leetcode | Maximum Length of Repeated Subarray
- LeetCode #718 Maximum Length of Repeated Subarray
- Maximum Length of Repeated Subarray解题报告
- 718.Maximum Length of Repeated Subarray(M)
- Leetcode | Maximum Length of Repeated Subarray
- LeetCode:Maximum Length of Repeated Subarray
- [leetcode]Maximum Length of Repeated Subarray
- 718. Maximum Length of Repeated Subarray
- 718. Maximum Length of Repeated Subarray
- 用IDEA在Tomcat上部署项目
- matplotlib tips
- leetcode: Exception: Type <class '__main__.ListNode'>: Not implemented
- Bootstrap折叠
- Mybatis学习笔记(四)【入门程序二】
- Maximum Length of Repeated Subarray
- JavaScript命名规范
- 【Java 并发】线程安全性
- 表单验证 二级联动 添加 删除
- Java for Web学习笔记(九十):消息和集群(5)利用websocket实现订阅和发布(上)
- laravel使用excel报错情况
- java面试需要掌握知识点
- lucene第一天
- Redis之 字符串(String)