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;    }};
原创粉丝点击